1#ifndef PSCF_AM_ITERATOR_TMPL_TPP
2#define PSCF_AM_ITERATOR_TMPL_TPP
11#include "AmIteratorTmpl.h"
12#include "NanException.h"
13#include <pscf/math/LuSolver.h>
14#include <util/format/Dbl.h>
15#include <util/format/Int.h>
16#include <util/misc/Timer.h>
17#include <util/misc/FileMaster.h>
31 template <
class Iterator,
class T>
52 template <
class Iterator,
class T>
59 template <
class Iterator,
class T>
91 template <
class Iterator,
class T>
95 setup(isContinuation);
110 nBasis_ = stateBasis_.size();
111 for (itr_ = 0; itr_ <
maxItr_; ++itr_) {
115 stateHistory_.append(temp_);
120 Log::file() <<
"------------------------------- \n";
132 residualHistory_.append(temp_);
140 Log::file() <<
", error = NaN" << std::endl;
149 if (verbose_ > 0 && verbose_ < 3) {
164 projectionRatio_ += projectionError_/preError_;
165 correctionRatio_ += correctionError_/preError_;
168 preError_ = correctionError_;
173 if (error_ < epsilon_) {
180 Log::file() <<
"-------------------------------\n";
210 addCorrection(stateTrial_, residualTrial_);
237 Log::file() <<
"Iterator failed to converge.\n";
242 template <
class Iterator,
class T>
246 double total = timerTotal_.time();
249 out <<
"Total" << std::setw(22)<<
"Per Iteration"
250 << std::setw(9) <<
"Fraction" <<
"\n";
251 out <<
"MDE solution: "
252 <<
Dbl(timerMDE_.time(), 9, 3) <<
" s, "
253 <<
Dbl(timerMDE_.time()/totalItr_, 9, 3) <<
" s, "
254 <<
Dbl(timerMDE_.time()/total, 9, 3) <<
"\n";
255 out <<
"residual computation: "
256 <<
Dbl(timerResid_.time(), 9, 3) <<
" s, "
257 <<
Dbl(timerResid_.time()/totalItr_, 9, 3) <<
" s, "
258 <<
Dbl(timerResid_.time()/total, 9, 3) <<
"\n";
259 out <<
"mixing coefficients: "
260 <<
Dbl(timerCoeff_.time(), 9, 3) <<
" s, "
261 <<
Dbl(timerCoeff_.time()/totalItr_, 9, 3) <<
" s, "
262 <<
Dbl(timerCoeff_.time()/total, 9, 3) <<
"\n";
263 out <<
"checking convergence: "
264 <<
Dbl(timerError_.time(), 9, 3) <<
" s, "
265 <<
Dbl(timerError_.time()/totalItr_, 9, 3) <<
" s, "
266 <<
Dbl(timerError_.time()/total, 9, 3) <<
"\n";
267 out <<
"updating guess: "
268 <<
Dbl(timerOmega_.time(), 9, 3) <<
" s, "
269 <<
Dbl(timerOmega_.time()/totalItr_, 9, 3) <<
" s, "
270 <<
Dbl(timerOmega_.time()/total, 9, 3)<<
"\n";
271 out <<
"total time: "
272 <<
Dbl(total, 9, 3) <<
" s, "
273 <<
Dbl(total/totalItr_, 9, 3) <<
" s \n";
278 out <<
"Average Projection Step Reduction Ratio: "
279 <<
Dbl(projectionRatio_/testCounter, 3, 3)<<
"\n";
280 out <<
"Average Correction Step Reduction Ratio: "
281 <<
Dbl(correctionRatio_/testCounter, 3, 3)<<
"\n";
286 template <
class Iterator,
class T>
304 template <
class Iterator,
class T>
317 std::string msg =
"Invalid iterator error type [";
319 msg +=
"] in parameter file";
327 template <
class Iterator,
class T>
349 template <
class Iterator,
class T>
355 useLambdaRamp_ = useLambdaRamp;
360 if (useLambdaRamp_) {
369 template <
class Iterator,
class T>
373 if (isAllocatedAM_)
return;
376 nElem_ = nElements();
380 residualHistory_.allocate(
maxHist_+1);
385 stateTrial_.allocate(nElem_);
386 residualTrial_.allocate(nElem_);
387 temp_.allocate(nElem_);
394 isAllocatedAM_ =
true;
401 template <
class Iterator,
class T>
412 const int nElem = nElements();
413 if (nElem != nElem_) {
415 RingBuffer<T>* buffers[4] = {&stateHistory_, &residualHistory_,
416 &stateBasis_, &residualBasis_};
417 for (
int k = 0; k < 4; ++k) {
421 for (
int i = 0; i < buffer.
capacity(); ++i) {
423 if (buffer[0].isAllocated()) {
424 buffer[0].deallocate();
429 stateTrial_.deallocate();
430 residualTrial_.deallocate();
433 residualTrial_.allocate(nElem_);
434 temp_.allocate(nElem_);
438 residualHistory_.clear();
439 stateHistory_.clear();
440 if (!isContinuation) {
442 residualBasis_.clear();
451 template <
class Iterator,
class T>
455 residualHistory_.clear();
456 stateHistory_.clear();
457 residualBasis_.clear();
466 template <
class Iterator,
class T>
467 void AmIteratorTmpl<Iterator,T>::computeTrialCoeff()
471 if (itr_ == 0 && nBasis_ == 0) {
473 for (m = 0; m < maxHist_; ++m) {
476 for (n = 0; n < maxHist_; ++n) {
484 if (itr_ == 0)
return;
487 if (stateHistory_.size() > 1) {
490 updateBasis(stateBasis_, stateHistory_);
493 updateBasis(residualBasis_, residualHistory_);
496 updateU(U_, residualBasis_);
501 nBasis_ = residualBasis_.size();
506 computeV(v_, residualHistory_[0], residualBasis_);
515 coeffs_[0] = v_[0] / U_(0,0);
517 if (nBasis_ < maxHist_) {
526 for (
int i = 0; i < nBasis_; ++i) {
528 for (
int j = 0; j < nBasis_; ++j) {
529 tempU(i,j) = U_(i,j);
536 solver.computeLU(tempU);
537 solver.solve(tempv, tempcoeffs);
540 for (
int i = 0; i < nBasis_; ++i) {
541 coeffs_[i] = tempcoeffs[i];
545 if (nBasis_ == maxHist_) {
549 solver.computeLU(U_);
550 solver.solve(v_, coeffs_);
555 for (
int i = 0; i < nBasis_; ++i) {
562 template <
class Iterator,
class T>
563 void AmIteratorTmpl<Iterator,T>::updateTrial()
567 setEqual(stateTrial_, stateHistory_[0]);
568 setEqual(residualTrial_, residualHistory_[0]);
574 addEqVectors(stateTrial_, stateBasis_, coeffs_);
575 addEqVectors(residualTrial_, residualBasis_, coeffs_);
597 projectionError_ = computeError(temp_, stateTrial_, errorType_, 0);
610 template <
class Iterator,
class T>
613 if (useLambdaRamp_ && (nBasis_ <
maxHist_)) {
614 double factor = 1.0 - pow(r_, nBasis_ + 1);
615 return factor*lambda_;
624 template <
class Iterator,
class T>
630 int nBasis = residualBasis.
size();
635 for (
int m = maxHist - 1; m > 0; --m) {
636 for (
int n = maxHist-1; n > 0; --n) {
642 for (
int m = 0; m < nBasis; ++m) {
643 double dotprod = dotProduct(residualBasis[0],residualBasis[m]);
657 template <
class Iterator,
class T>
658 void AmIteratorTmpl<Iterator, T>::computeV(
660 T
const & resCurrent,
663 int nBasis = residualBasis.
size();
665 for (
int m = 0; m < nBasis; ++m) {
666 v[m] = dotProduct(resCurrent, residualBasis[m]);
673 template <
class Iterator,
class T>
683 double normRes = norm(residTrial);
686 if (std::isnan(normRes)) {
696 error = maxAbs(residTrial);
700 error = normRes/sqrt(nElements());
701 }
else if (
errorType ==
"relNormResid") {
702 double normField = norm(stateTrial);
703 error = normRes/normField;
705 UTIL_THROW(
"Invalid iterator error type in parameter file.");
711 double maxRes = maxAbs(residTrial);
714 double rmsRes = normRes/sqrt(nElements());
717 double normField = norm(stateTrial);
718 double relNormRes = normRes/normField;
727 }
else if (
errorType ==
"relNormResid") {
730 UTIL_THROW(
"Invalid iterator error type in parameter file.");
734 Log::file() <<
"Max Residual = " <<
Dbl(maxRes,15) <<
"\n";
735 Log::file() <<
"Residual Norm = " <<
Dbl(normRes,15) <<
"\n";
736 Log::file() <<
"RMS Residual = " <<
Dbl(rmsRes,15) <<
"\n";
747 template <
class Iterator,
class T>
750 return computeError(residualHistory_[0], stateHistory_[0],
757 template <
class Iterator,
class T>
759 AmIteratorTmpl<Iterator,T>::updateBasis(
RingBuffer<T> & basis,
767 if (basis[0].isAllocated()) {
768 UTIL_CHECK(basis[0].capacity() == history[0].capacity());
770 basis[0].
allocate(history[0].capacity());
774 subVV(basis[0], history[0], history[1]);
780 template <
class Iterator,
class T>
782 AmIteratorTmpl<Iterator,T>::addEqVectors(T& v,
786 int nBasis = basis.
size();
788 for (
int i = 0; i < nBasis; i++) {
789 addEqVc(v, basis[i], coeffs[i]);
796 template <
class Iterator,
class T>
798 AmIteratorTmpl<Iterator,T>::addCorrection(T& stateTrial,
799 T
const & residualTrial)
801 double lambda = computeLambda();
802 addEqVc(stateTrial, residualTrial, lambda);
810 template <
class Iterator,
class T>
811 double AmIteratorTmpl<Iterator,T>::norm(T
const & a)
813 double normSq = dotProduct(a, a);
820 template <
class Iterator,
class T>
821 void AmIteratorTmpl<Iterator,T>::setEqual(T& a, T
const & b)
827 template <
class Iterator,
class T>
829 AmIteratorTmpl<Iterator,T>::dotProduct(T
const & a, T
const & b)
835 template <
class Iterator,
class T>
836 double AmIteratorTmpl<Iterator,T>::maxAbs(T
const & a)
842 template <
class Iterator,
class T>
843 void AmIteratorTmpl<Iterator,T>::subVV(T& a, T
const & b, T
const & c)
849 template <
class Iterator,
class T>
850 void AmIteratorTmpl<Iterator,T>::addEqVc(T& a, T
const & b,
double c)
Template for Anderson mixing iterator algorithm.
virtual void setup(bool isContinuation)
Initialize just before entry to iterative loop.
ScalarParam< Type > & read(std::istream &in, const char *label, Type &value)
Add and read a new required ScalarParam < Type > object.
void readMixingParameters(std::istream &in, bool useLambdaRamp=true)
Read optional parameters used in default correction algorithm.
void allocateAM()
Allocate memory required by AM algorithm, if necessary.
bool isAllocatedAM() const
Have data structures required by the AM algorithm been allocated?
virtual void clear()
Clear information about history.
void outputTimers(std::ostream &out) const
Log output timing results.
std::string errorType() const
Get error type string.
ScalarParam< Type > & readOptional(std::istream &in, const char *label, Type &value)
void clearTimers()
Clear timers.
int verbose() const
Verbosity level, allowed values 0, 1, or 2.
~AmIteratorTmpl()
Destructor.
void readErrorType(std::istream &in)
Read and validate the optional errorType string parameter.
int verbose_
Verbosity level.
double epsilon_
Error tolerance.
AmIteratorTmpl()
Constructor.
virtual double computeLambda()
Compute mixing parameter for correction step of Anderson mixing.
virtual bool isValidErrorType()
Checks if a string is a valid error type.
int maxItr_
Maximum number of iterations to attempt.
virtual double computeError(DArray< double > &residTrial, DArray< double > &stateTrial, std::string errorType, int verbose)
std::string errorType_
Type of error criterion used to test convergence.
virtual void readParameters(std::istream &in)
Read all parameters and initialize.
int maxHist_
Maximum number of basis vectors in AM algorithm.
int solve(bool isContinuation=false)
Iterate to a solution.
Solve Ax=b by LU decomposition of A.
void allocate(int n)
Allocate memory.
Exception thrown when not-a-number (NaN) is encountered.
NanException(const char *function, const char *file, int line, int echo=1)
Constructor.
int capacity() const
Return allocated size.
Dynamically allocatable contiguous array template.
void allocate(int capacity)
Allocate the underlying C array.
Dynamically allocated Matrix.
void allocate(int capacity1, int capacity2)
Allocate memory for a matrix.
Dbl()
Default constructor.
Int()
Default constructor.
static std::ostream & file()
Get log ostream by reference.
int capacity1() const
Get number of rows (range of the first array index).
void setClassName(const char *className)
Set class name string.
Class for storing history of previous values in an array.
void allocate(int capacity)
Allocate a new empty buffer.
void clear()
Set previously allocated buffer to empty state.
int capacity() const
Return the capacity of the buffer.
void advance()
Advances the pointer to an added element without assigning a value.
int size() const
Return number of values currently in the buffer.
#define UTIL_CHECK(condition)
Assertion macro suitable for serial or parallel production code.
#define UTIL_THROW(msg)
Macro for throwing an Exception, reporting function, file and line number.
double innerProduct(Array< double > const &a, Array< double > const &b)
Compute Euclidean inner product of two real arrays .
double maxAbs(Array< double > const &in)
Get maximum absolute magnitude of array elements .
void eqV(Array< double > &a, Array< double > const &b, const int beginIdA, const int beginIdB, const int n)
Vector assignment, a[i] = b[i] (real, slice).
void subVV(Array< double > &a, Array< double > const &b, Array< double > const &c)
Vector-vector subtraction, a[i] = b[i] - c[i] (real).
void addEqVc(Array< double > &a, Array< double > const &b, const double c)
Add scaled vector in-place, a[i] += b[i]*c (real).
PSCF package top-level namespace.