13#ifndef CG_IMPLEMENTATION_HH
14#define CG_IMPLEMENTATION_HH
43 template <
class Domain,
class Range>
46 if (
dynamic_cast<Dune::Richardson<Domain,Range> const*
>(p))
49 return sp->requiresInitializedInput();
76 template <
class Scalar>
80 template <
class X,
class Xstar,
class Derived>
101 theta += (1-qAq)/std::fabs(qPq);
102 if(
verbose > 0 ) std::cout <<
"Regularization: Computed theta: " <<
theta <<
'\n';
103 theta = std::min(std::max(2*oldTheta,
theta),1e2*oldTheta);
105 std::cout <<
"Regularization: Updating theta from " << oldTheta <<
" to "
111 r.axpy(-alpha*
theta,Pq);
121 template <
class X,
class Xstar,
class>
136 template <
class X,
class Xstar,
class Derived, CGImplementationType impl>
139 typedef typename std::conditional<
217 template <
typename... Args>
232 CGFminModel(
double quadraticPart_,
double linearPart_,
double omegaL_,
233 double dndn_,
double dnd_,
double dd_)
240 double normSquared =
dndn + t*
dnd + t*t*
dd;
281 :
public Dune::InverseOperator<X,Xstar>
285 enum class Result { Converged, Failed, EncounteredNonConvexity, TruncatedAtNonConvexity };
316 int verbose_ = 0,
double eps_ = 1e-15,
318 : TimerPolicy(timer_),
321 proxyOp(op_,zeroDp), op(op_),
322 proxyPrec(prec_,zeroDp), prec(prec_),
323 terminate(terminate_), verbose(verbose_), eps(eps_),
340 CGBase(Dune::LinearOperator<X,Xstar>& op_,
341 Dune::Preconditioner<X,Xstar>& prec_,
344 int verbose_ = 0,
double eps_ = 1e-15,
346 : TimerPolicy(timer_),
349 proxyOp(op_,dp_), op(proxyOp),
350 proxyPrec(prec_,dp_), prec(proxyPrec),
351 terminate(terminate_), verbose(verbose_), eps(eps_),
369 CGBase(Dune::LinearOperator<X,Xstar>& op_,
370 Dune::Preconditioner<X,Xstar>& prec_,
374 int verbose_ = 0,
double eps_ = 1e-15,
376 : TimerPolicy(timer_),
379 proxyOp(op_,dp_), op(proxyOp),
380 proxyPrec(prec_,dp_), prec(proxyPrec),
381 terminate(terminate_), verbose(verbose_), eps(eps_),
387 Dune::InverseOperatorResult res;
397 virtual void apply(X& u, Xstar&b,
Real tolerance, Dune::InverseOperatorResult& res)
399 terminate.tolerance(tolerance);
403 virtual void apply(X& u, Xstar& b, Dune::InverseOperatorResult& res)
412 result = Result::Failed;
413 while( result != Result::Converged && result != Result::TruncatedAtNonConvexity )
423 std::cout <<
"=== rate=" << res.conv_rate
424 <<
", T=" << res.elapsed
425 <<
", TIT=" << res.elapsed/step
426 <<
", IT=" << step <<
'\n';
432 int cgLoop (X& u, Xstar& b, Dune::InverseOperatorResult& res)
440 result = Result::Failed;
441 res.converged =
false;
445 const int maxNoiterations=terminate.getMaxIterationSteps();
449 op.applyscaleadd(-1,u,r);
451 std::unique_ptr<X> rq(
new X(u)); *rq = 0;
458 std::unique_ptr<X> q(
new X(*rq));
464 Real alpha = 0, beta = 0;
467 Real sigma = std::abs(op.dp(*rq,r));
469 terminate.residual(
Real(sigma));
470 double const sigma0 = sigma;
473 std::cout <<
"=== Kaskade7 IterateType::CG" <<
'\n';
475 this->printHeader(std::cout);
476 this->printOutput(std::cout,(
double)0,sigma0);
481 if(!std::is_same<Functor,DoNotAlwaysRegularize>::value)
487 double dHd = op.dp(*q,Hd);
489 double initialThetaGuess = 1./tau - dHd/sigma;
490 std::cout <<
"CG: TAU = " << tau <<
'\n';
491 std::cout <<
"CG: INITIAL GUESS FOR THETA = " << initialThetaGuess <<
'\n';
495 for ( step = 1; step<=maxNoiterations; step++ )
499 field_type qAq = op.applyDp(*q,Aq);
502 if (std::isnan(qAq)) std::cerr <<
"qAq is nan\n";
505 field_type qPq = op.dp(*q,Pq);
507 this->regularize(qAq,qPq);
510 energyNorm2 += alpha*qAq;
511 alphas.push_back(alpha);
514 if( std::fabs(qAq) < eps*eps )
517 std::cout << pre <<
"Terminating due to numerically almost vanishing step."
519 result = Result::Converged;
520 res.converged =
true;
528 std::cout << pre <<
"Direction of negative curvature encountered in standard "
529 <<
"IterateType::CG implementation!" <<
'\n';
530 std::cout << pre <<
"Either something is wrong with your operator or you should use "
531 <<
"TCG, RCG or HCG. Terminating IterateType::CG!" <<
'\n';
543 if( step == 1 ) u.axpy(1.0,*q);
545 std::cout << pre <<
"Truncating at nonconvexity in iteration "
546 << step <<
": " << qAq <<
'\n';
547 result = Result::TruncatedAtNonConvexity;
553 this->updateRegularization(qAq,qPq);
555 std::cout << pre <<
"Regularizing at nonconvexity in iteration "
556 << step <<
"." <<
'\n';
557 result = Result::EncounteredNonConvexity;
566 terminate.step(
Real(sigma*alpha));
572 result = Result::Converged;
573 res.converged =
true;
579 this->adjustResidual(r,alpha,Pq);
588 terminate.residual(
Real(sigmaNew));
590 if (verbose>1) this->printOutput(std::cout,(
double)step,std::abs(sigmaNew),std::abs(sigma));
593 if (std::abs(sigmaNew) < 1e-28*sigma0)
596 std::cout << pre <<
"Convergence due to vanishing residual." <<
'\n';
597 result = Result::Converged;
598 res.converged =
true;
602 beta = sigmaNew/sigma;
603 betas.push_back(beta);
615 if (verbose>0) this->printOutput(std::cout,(
double)step,std::abs(sigma));
616 res.iterations = step;
617 res.reduction = std::sqrt(std::abs(sigma)/sigma0);
618 res.conv_rate = pow(res.reduction,1.0/step);
619 res.elapsed = watch.elapsed();
627 return result==Result::EncounteredNonConvexity || result==Result::TruncatedAtNonConvexity;
638 virtual Dune::SolverCategory::Category
category()
const override
640 return Dune::SolverCategory::sequential;
684 if (alphas.size() < 2)
687 int const k = alphas.size();
690 std::vector<Real>
diag(k);
691 std::vector<Real> subdiag(k-1);
692 for (
int i=0; i<k; ++i)
694 Real d = 1/alphas[i];
697 d += betas[i-1]/alphas[i-1];
698 subdiag[i-1] = std::sqrt(betas[i-1])/alphas[i-1];
707 std::vector<Real> w(k);
717 Real lambdaMax = w.back();
718 Real lambdaMin = w.front();
722 Real kappa = lambdaMax/lambdaMin;
736 Real sMax = std::abs(z[(k-1)*k + (k-1)]);
737 Real sMin = std::abs(z[0*k + (k-1)]);
740 Real betaK = std::sqrt(betas[k-2])/alphas[k-2];
747 Real slack = 1 + 1e-8;
748 Real errMax = betaK * sMax * slack;
749 Real errMin = betaK * sMin * slack;
750 Real lambdaMaxUp = lambdaMax + errMax;
751 Real lambdaMinLo = lambdaMin - errMin;
752 if (lambdaMinLo <= 0)
753 *kappaUpper = std::numeric_limits<Real>::infinity();
755 *kappaUpper = lambdaMaxUp/lambdaMinLo;
790 std::vector<Real> alphas;
791 std::vector<Real> betas;
794 std::string pre = std::string(
"KASKADE IterateType::PCG: ");
CGBase(Dune::LinearOperator< X, Xstar > &op_, Dune::Preconditioner< X, Xstar > &prec_, DualPairing< X, Xstar > const &dp_, PCGTerminationCriterion< Real > &terminate_, Functor f_, int verbose_=0, double eps_=1e-15, Timings &timer_=Timings::instance())
Set up conjugate gradient solver with a functor for an initial regularization guess.
ScalarTraits< field_type >::Real Real
virtual void apply(X &u, Xstar &b, Real tolerance, Dune::InverseOperatorResult &res)
virtual Dune::SolverCategory::Category category() const override
returns the category of the operator
bool encounteredNonConvexity() const
virtual void apply(X &u, Xstar &b, Dune::InverseOperatorResult &res)
CGBase(SymmetricLinearOperator< X, Xstar > &op_, SymmetricPreconditioner< X, Xstar > &prec_, PCGTerminationCriterion< Real > &terminate_, int verbose_=0, double eps_=1e-15, Timings &timer_=Timings::instance())
Set up conjugate gradient solver.
void apply(X &u, Xstar &b)
CGBase(Dune::LinearOperator< X, Xstar > &op_, Dune::Preconditioner< X, Xstar > &prec_, DualPairing< X, Xstar > const &dp_, PCGTerminationCriterion< Real > &terminate_, int verbose_=0, double eps_=1e-15, Timings &timer_=Timings::instance())
Set up conjugate gradient solver.
int cgLoop(X &u, Xstar &b, Dune::InverseOperatorResult &res)
Real cond(Real *kappaUpper=nullptr) const
Condition number estimate of the preconditioned system.
double getSolutionEnergyNormEstimate()
Abstract base class for dual pairing of and its dual space .
A base class for linear algebra exceptions.
Interface for IterateType::PCG termination criterion policy classes.
Helper class for working with (real or complex) scalar field types.
Scalar Real
The real type on which the scalar field is based.
Interface for symmetric linear operators.
Wrapper class to present (hopefully) symmetric linear operators in the SymmetricLinearOperator interf...
Interface for symmetric preconditioners.
Wrapper class presenting a symmetric preconditioner interface for any preconditioner.
Supports gathering and reporting execution times information for nested program parts.
static Timings & instance()
Returns a reference to a single default instance.
Zero dual pairing implementation (mainly useful whenever a dual pairing is needed for formal language...
bool requiresInitializedInput(Dune::Preconditioner< Domain, Range > const *p)
Whether a preconditioner needs zero initialized result vector or not.
Dune::FieldMatrix< Entry, n, n > diag(Dune::FieldVector< Entry, n > const &d)
Creates a fixed-size diagonal matrix from the given diagonal vector.
void stev(char jobz, int n, Scalar *diag, Scalar *subdiag, typename ScalarTraits< Scalar >::Real *w, Scalar *z=nullptr)
Computes all eigenvalues (and optionally eigenvectors) of a symmetric tridiagonal matrix via LAPACK *...
std::conditional< impl==CGImplementationType::STANDARD||impl==CGImplementationType::TRUNCATED, NoRegularization< X, Xstar, Derived >, Regularization< X, Xstar, Derived > >::type type
void regularize(double &, double)
void adjustResidual(Xstar &, double, Xstar const &)
void initializeRegularization()
void updateRegularization(double, double)
NoRegularization(double, int)
ScalarTraits< typenameGetScalar< X >::type >::Real Real
void initializeRegularization()
void regularize(double &qAq, double qPq)
void updateRegularization(double qAq, double qPq)
void adjustResidual(Xstar &r, double alpha, Xstar const &Pq)
Regularization(double eps_, int verbose_)
CGFminModel & operator=(CGFminModel const &)=default
CGFminModel(double quadraticPart_, double linearPart_, double omegaL_, double dndn_, double dnd_, double dd_)
CGFminModel(CGFminModel const &)=default
double operator()(double t)
void init(const Args &...)
Timer policy that does not measure anything.
DoNotMeasureTime(Timings &=Timings::instance())
MeasureTime(Timings &timer_=Timings::instance())