2015-06-05 18:16:25 +01:00
|
|
|
#ifndef GRID_CONJUGATE_RESIDUAL_H
|
|
|
|
#define GRID_CONJUGATE_RESIDUAL_H
|
|
|
|
|
|
|
|
namespace Grid {
|
|
|
|
|
|
|
|
/////////////////////////////////////////////////////////////
|
|
|
|
// Base classes for iterative processes based on operators
|
|
|
|
// single input vec, single output vec.
|
|
|
|
/////////////////////////////////////////////////////////////
|
|
|
|
|
|
|
|
template<class Field>
|
|
|
|
class ConjugateResidual : public OperatorFunction<Field> {
|
|
|
|
public:
|
|
|
|
RealD Tolerance;
|
|
|
|
Integer MaxIterations;
|
|
|
|
int verbose;
|
|
|
|
|
|
|
|
ConjugateResidual(RealD tol,Integer maxit) : Tolerance(tol), MaxIterations(maxit) {
|
2015-06-20 22:22:56 +01:00
|
|
|
verbose=0;
|
2015-06-05 18:16:25 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
void operator() (LinearOperatorBase<Field> &Linop,const Field &src, Field &psi){
|
|
|
|
|
|
|
|
RealD a, b, c, d;
|
|
|
|
RealD cp, ssq,rsq;
|
|
|
|
|
|
|
|
RealD rAr, rAAr, rArp;
|
|
|
|
RealD pAp, pAAp;
|
|
|
|
|
|
|
|
GridBase *grid = src._grid;
|
|
|
|
psi=zero;
|
|
|
|
Field r(grid), p(grid), Ap(grid), Ar(grid);
|
|
|
|
|
|
|
|
r=src;
|
|
|
|
p=src;
|
|
|
|
|
|
|
|
Linop.HermOpAndNorm(p,Ap,pAp,pAAp);
|
|
|
|
Linop.HermOpAndNorm(r,Ar,rAr,rAAr);
|
|
|
|
|
|
|
|
cp =norm2(r);
|
|
|
|
ssq=norm2(src);
|
|
|
|
rsq=Tolerance*Tolerance*ssq;
|
|
|
|
|
2015-07-23 17:31:13 +01:00
|
|
|
if (verbose) std::cout<<GridLogMessage<<"ConjugateResidual: iteration " <<0<<" residual "<<cp<< " target"<< rsq<<std::endl;
|
2015-06-05 18:16:25 +01:00
|
|
|
|
|
|
|
for(int k=1;k<MaxIterations;k++){
|
|
|
|
|
|
|
|
a = rAr/pAAp;
|
|
|
|
|
|
|
|
axpy(psi,a,p,psi);
|
|
|
|
|
|
|
|
cp = axpy_norm(r,-a,Ap,r);
|
|
|
|
|
|
|
|
rArp=rAr;
|
|
|
|
|
|
|
|
Linop.HermOpAndNorm(r,Ar,rAr,rAAr);
|
|
|
|
|
|
|
|
b =rAr/rArp;
|
|
|
|
|
|
|
|
axpy(p,b,p,r);
|
|
|
|
pAAp=axpy_norm(Ap,b,Ap,Ar);
|
2015-06-21 10:58:46 +01:00
|
|
|
|
2015-07-23 17:31:13 +01:00
|
|
|
if(verbose) std::cout<<GridLogMessage<<"ConjugateResidual: iteration " <<k<<" residual "<<cp<< " target"<< rsq<<std::endl;
|
2015-06-05 18:16:25 +01:00
|
|
|
|
|
|
|
if(cp<rsq) {
|
|
|
|
Linop.HermOp(psi,Ap);
|
|
|
|
axpy(r,-1.0,src,Ap);
|
2015-06-21 10:58:46 +01:00
|
|
|
RealD true_resid = norm2(r)/ssq;
|
2015-07-23 17:31:13 +01:00
|
|
|
std::cout<<GridLogMessage<<"ConjugateResidual: Converged on iteration " <<k
|
2015-06-20 22:22:56 +01:00
|
|
|
<< " computed residual "<<sqrt(cp/ssq)
|
2015-06-21 10:58:46 +01:00
|
|
|
<< " true residual "<<sqrt(true_resid)
|
2015-06-20 22:22:56 +01:00
|
|
|
<< " target " <<Tolerance <<std::endl;
|
2015-06-05 18:16:25 +01:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2015-07-23 17:31:13 +01:00
|
|
|
std::cout<<GridLogMessage<<"ConjugateResidual did NOT converge"<<std::endl;
|
2015-06-05 18:16:25 +01:00
|
|
|
assert(0);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
#endif
|