PSCF v1.5.0
AmIteratorTmpl.tpp
1#ifndef PSCF_AM_ITERATOR_TMPL_TPP
2#define PSCF_AM_ITERATOR_TMPL_TPP
3
4/*
5* PSCF - Polymer Self-Consistent Field
6*
7* Copyright 2015 - 2026, David Morse (morse012@um.edu) and co-authors
8* Distributed under the terms of the GNU General Public License.
9*/
10
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>
18
19#include <cmath>
20
21namespace Pscf
22{
23
24 using namespace Util;
25
26 // Public member functions
27
28 /*
29 * Constructor
30 */
31 template <class Iterator, class T>
33 : epsilon_(0),
34 maxItr_(200),
35 maxHist_(50),
36 verbose_(1),
37 errorType_("relNormResid"),
38 error_(0.0),
39 nBasis_(0),
40 itr_(0),
41 totalItr_(0),
42 nElem_(0),
43 lambda_(1.0),
44 r_(0.9),
45 useLambdaRamp_(true),
46 isAllocatedAM_(false)
47 { ParamComposite::setClassName("AmIteratorTmpl"); }
48
49 /*
50 * Destructor
51 */
52 template <class Iterator, class T>
55
56 /*
57 * Read parameter file block.
58 */
59 template <class Iterator, class T>
61 {
62
63 // Error tolerance for scalar error. Stop when error < epsilon.
64 read(in, "epsilon", epsilon_);
65
66 // Maximum number of iterations (optional)
67 // Default set in constructor (200)
68 readOptional(in, "maxItr", maxItr_);
69
70 // Maximum number of previous vectors in history (optional)
71 // Default set in constructor (50)
72 readOptional(in, "maxHist", maxHist_);
73
74 // Verbosity level of error reporting, values 0-3 (optional)
75 // Initialized to 1 by default in constructor
76 // verbose_ = 0 => FTS
77 // verbose_ = 1 => concise
78 // verbose_ = 2 => report all error measures at end
79 // verbose_ = 3 => report all error measures every iteration
80 readOptional(in, "verbose", verbose_);
82 #ifdef PSCF_AM_TEST
83 // Default set to be false
84 readOptional(in, "hasAmTest", hasAmTest_);
85 #endif
86 }
87
88 /*
89 * Iteratively solve a fixed-point problem.
90 */
91 template <class Iterator, class T>
92 int AmIteratorTmpl<Iterator,T>::solve(bool isContinuation)
93 {
94 // Initialization and allocate operations on entry to loop.
95 setup(isContinuation);
96
97 // Preconditions for generic Anderson-mixing (AM) algorithm.
98 UTIL_CHECK(hasInitialGuess());
99 UTIL_CHECK(isAllocatedAM_);
100
101 // Start overall timer
102 timerTotal_.start();
103
104 // Solve MDE for initial state
105 timerMDE_.start();
106 evaluate();
107 timerMDE_.stop();
108
109 // Iterative loop
110 nBasis_ = stateBasis_.size();
111 for (itr_ = 0; itr_ < maxItr_; ++itr_) {
112
113 // Append current state to stateHistory_ ringbuffer
114 getCurrent(temp_);
115 stateHistory_.append(temp_);
116
117 timerAM_.start();
118
119 if (verbose_ > 2) {
120 Log::file() << "------------------------------- \n";
121 }
123 if (verbose_ > 0){
124 Log::file() << " Iteration " << Int(itr_,5);
125 }
126
127 // Compute current residual vector, store in temp_
128 timerResid_.start();
129 getResidual(temp_);
130
131 // Append current residual to residualHistory_ ring buffer
132 residualHistory_.append(temp_);
133 timerResid_.stop();
134
135 // Compute scalar error used to test convergence
136 timerError_.start();
137 try {
138 error_ = computeError(verbose_);
139 } catch (NanException const &) {
140 Log::file() << ", error = NaN" << std::endl;
141 // Stop the timers started in this iteration, so that the
142 // next call to solve() can restart them.
143 timerError_.stop();
144 timerAM_.stop();
145 break;
146 // If a NanException is caught, break from iterative loop.
147 // Completing the loop is treated as failure to converge.
148 }
149 if (verbose_ > 0 && verbose_ < 3) {
150 Log::file() << ", error = " << Dbl(error_, 15)
151 << std::endl;
152 }
153 timerError_.stop();
155 // Output additional details of this iteration to the log file
156 outputToLog();
157
158 #ifdef PSCF_AM_TEST
159 // Compute errors and ratios used for algorithm testing
160 if (hasAmTest_){
161 // Compute errors and ratios used for algorithm testing
162 correctionError_ = computeError(0);
163 if (itr_ > 0) {
164 projectionRatio_ += projectionError_/preError_;
165 correctionRatio_ += correctionError_/preError_;
166 testCounter ++;
167 }
168 preError_ = correctionError_;
169 }
170 #endif
171
172 // Check for convergence
173 if (error_ < epsilon_) {
175 // Stop timers
176 timerAM_.stop();
177 timerTotal_.stop();
178
179 if (verbose_ > 2) {
180 Log::file() << "-------------------------------\n";
181 }
183 if (verbose_ > 0) {
184 Log::file() << " Converged\n";
185 }
186
187 // Output error report if not done previously
188 if (verbose_ == 2) {
189 Log::file() << "\n";
190 computeError(2);
191 }
192
193 totalItr_ += itr_;
195 // Successful completion (i.e., converged within tolerance)
196 return 0;
197
198 } else {
199
200 // Compute optimal coefficients for basis vectors
201 timerCoeff_.start();
202 computeTrialCoeff();
203 timerCoeff_.stop();
204
205 // Compute updated trial state and residual vectors
206 timerOmega_.start();
207 updateTrial();
208
209 // Correction (or "mixing") step
210 addCorrection(stateTrial_, residualTrial_);
211
212 // Update the parent system using new trial state
213 update(stateTrial_);
214
215 timerOmega_.stop();
216 timerAM_.stop();
217
218 // Perform the main calculation of the parent system -
219 // Solve MDEs, compute phi's, compute stress if needed
220 timerMDE_.start();
221 evaluate();
222 timerMDE_.stop();
223 }
224
225 }
226
227 // Failure: Counter itr_ reached maxItr_ without converging,
228 // or loop was exited because of NaN error
229
230 // Discard the history and basis vectors of the failed solve. A
231 // caller that retries (e.g., a sweep that backtracks with
232 // isContinuation = true) would otherwise reapply the displacement
233 // that led to the failure at the first iteration of the retry.
234 clear();
235
236 timerTotal_.stop();
237 Log::file() << "Iterator failed to converge.\n";
238 return 1;
239
240 }
241
242 template <class Iterator, class T>
243 void AmIteratorTmpl<Iterator,T>::outputTimers(std::ostream& out) const
244 {
245 // Output timing results, if requested.
246 double total = timerTotal_.time();
247 out << "\n";
248 out << " ";
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";
274 out << "\n";
275
276 #ifdef PSCF_AM_TEST
277 if (hasAmTest_){
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";
282 }
283 #endif
284 }
285
286 template <class Iterator, class T>
288 {
289 timerMDE_.clear();
290 timerResid_.clear();
291 timerError_.clear();
292 timerCoeff_.clear();
293 timerOmega_.clear();
294 timerAM_.clear();
295 timerTotal_.clear();
296 totalItr_ = 0;
297 }
298
299 // Protected member functions - Initialization
300
301 /*
302 * Read and validate optional errorType string parameter.
303 */
304 template <class Iterator, class T>
306 {
307 // Note: errorType_ is initialized to "relNormResid" in constructor
308
309 // Read optional errorType_ string if present
310 readOptional(in, "errorType", errorType_);
311
312 // Check validity, normalize to standard form
313 bool isValid = isValidErrorType();
314
315 // If not valid, throw Exception with error message
316 if (!isValid) {
317 std::string msg = "Invalid iterator error type [";
318 msg += errorType_;
319 msg += "] in parameter file";
320 UTIL_THROW(msg.c_str());
321 }
322 }
323
324 /*
325 * Check validity of errorType_ string and normalize if valid.
326 */
327 template <class Iterator, class T>
329 {
330 // Process possible synonyms
331 if (errorType_ == "norm") errorType_ = "normResid";
332 if (errorType_ == "rms") errorType_ = "rmsResid";
333 if (errorType_ == "max") errorType_ = "maxResid";
334 if (errorType_ == "relNorm") errorType_ = "relNormResid";
335
336 // Check value
337 bool valid;
338 valid = (errorType_ == "normResid"
339 || errorType_ == "rmsResid"
340 || errorType_ == "maxResid"
341 || errorType_ == "relNormResid");
342 return valid;
343
344 }
345
346 /*
347 * Read and validate optional errorType string parameter.
348 */
349 template <class Iterator, class T>
350 void
352 bool useLambdaRamp)
353 {
354 // Set default parameter for useLambdaRamp_
355 useLambdaRamp_ = useLambdaRamp;
356
357 // Optionally read mixing parameters
358 readOptional(in, "lambda", lambda_);
359 readOptional(in, "useLambdaRamp", useLambdaRamp_);
360 if (useLambdaRamp_) {
361 readOptional(in, "r", r_);
362 }
363 }
364
365 /*
366 * Allocate memory required by the AM algorithm, if needed.
367 * (protected, non-virtual)
368 */
369 template <class Iterator, class T>
371 {
372 // If already allocated, do nothing and return
373 if (isAllocatedAM_) return;
374
375 // Compute and set number of elements in a residual vector
376 nElem_ = nElements();
377
378 // Allocate ring buffers
379 stateHistory_.allocate(maxHist_+1);
380 residualHistory_.allocate(maxHist_+1);
381 stateBasis_.allocate(maxHist_);
382 residualBasis_.allocate(maxHist_);
383
384 // Allocate arrays used in iteration
385 stateTrial_.allocate(nElem_);
386 residualTrial_.allocate(nElem_);
387 temp_.allocate(nElem_);
388
389 // Allocate arrays/matrices used in coefficient calculation
390 U_.allocate(maxHist_, maxHist_);
391 v_.allocate(maxHist_);
392 coeffs_.allocate(maxHist_);
393
394 isAllocatedAM_ = true;
395 }
396
397 /*
398 * Initialize just before entry to iterative loop.
399 * (virtual)
400 */
401 template <class Iterator, class T>
402 void AmIteratorTmpl<Iterator,T>::setup(bool isContinuation)
403 {
404 if (!isAllocatedAM()) {
405 allocateAM();
406 } else {
407
408 // If the number of elements of a vector has changed since the
409 // allocation (e.g., after a change in the set of flexible unit
410 // cell parameters), reallocate all vectors, and discard all
411 // histories and basis vectors, also for a continuation.
412 const int nElem = nElements();
413 if (nElem != nElem_) {
414 nElem_ = nElem;
415 RingBuffer<T>* buffers[4] = {&stateHistory_, &residualHistory_,
416 &stateBasis_, &residualBasis_};
417 for (int k = 0; k < 4; ++k) {
418 RingBuffer<T>& buffer = *buffers[k];
419 // Visit every slot, including slots outside the history
420 buffer.clear();
421 for (int i = 0; i < buffer.capacity(); ++i) {
422 buffer.advance();
423 if (buffer[0].isAllocated()) {
424 buffer[0].deallocate();
425 }
426 }
427 buffer.clear();
428 }
429 stateTrial_.deallocate();
430 residualTrial_.deallocate();
431 temp_.deallocate();
432 stateTrial_.allocate(nElem_);
433 residualTrial_.allocate(nElem_);
434 temp_.allocate(nElem_);
435 }
436
437 // Clear residual and state history buffers
438 residualHistory_.clear();
439 stateHistory_.clear();
440 if (!isContinuation) {
441 // Clear bases iff not a continuation
442 residualBasis_.clear();
443 stateBasis_.clear();
444 }
445 }
446 }
447
448 /*
449 * Clear all history and basis vector data.
450 */
451 template <class Iterator, class T>
453 {
454 UTIL_CHECK(isAllocatedAM_);
455 residualHistory_.clear();
456 stateHistory_.clear();
457 residualBasis_.clear();
458 stateBasis_.clear();
459 }
460
461 // Private non-virtual member functions
462
463 /*
464 * Compute optimal coefficients of basis vectors.
465 */
466 template <class Iterator, class T>
467 void AmIteratorTmpl<Iterator,T>::computeTrialCoeff()
468 {
469 // If first iteration and bases are empty
470 // then initialize U, v and coeff arrays
471 if (itr_ == 0 && nBasis_ == 0) {
472 int m, n;
473 for (m = 0; m < maxHist_; ++m) {
474 v_[m] = 0.0;
475 coeffs_[m] = 0.0;
476 for (n = 0; n < maxHist_; ++n) {
477 U_(m, n) = 0.0;
478 }
479 }
480 return;
481 }
482
483 // Do nothing else on first iteration
484 if (itr_ == 0) return;
485
486 // Update stateBasis_, residualBasis_, U_ matrix and v_ vector
487 if (stateHistory_.size() > 1) {
488
489 // Update basis spanning differences of past state vectors
490 updateBasis(stateBasis_, stateHistory_);
491
492 // Update basis spanning differences of past residual vectors
493 updateBasis(residualBasis_, residualHistory_);
494
495 // Update the U matrix and v vector.
496 updateU(U_, residualBasis_);
497
498 }
499
500 // Update nBasis_
501 nBasis_ = residualBasis_.size();
502 UTIL_CHECK(nBasis_ > 0);
503 UTIL_CHECK(stateBasis_.size() == nBasis_);
504
505 // Update v_ vector (dot product of basis vectors and residual)
506 computeV(v_, residualHistory_[0], residualBasis_);
507
508 // Solution of the matrix problem U coeffs_ = -v yields a coeff
509 // vector that minimizes the norm of the residual. Below, we:
510 // 1. Solve matrix equation: U coeffs_ = v
511 // 2. Flip the sign of the resulting coeffs_ vector
512
513 if (nBasis_ == 1) {
514 // Solve explicitly for coefficient
515 coeffs_[0] = v_[0] / U_(0,0);
516 } else
517 if (nBasis_ < maxHist_) {
518
519 // Create temporary smaller version of U_, v_, coeffs_ .
520 // This avoids reallocation of U_ with each iteration.
521 DMatrix<double> tempU;
522 DArray<double> tempv, tempcoeffs;
523 tempU.allocate(nBasis_,nBasis_);
524 tempv.allocate(nBasis_);
525 tempcoeffs.allocate(nBasis_);
526 for (int i = 0; i < nBasis_; ++i) {
527 tempv[i] = v_[i];
528 for (int j = 0; j < nBasis_; ++j) {
529 tempU(i,j) = U_(i,j);
530 }
531 }
532
533 // Solve matrix equation
534 LuSolver solver;
535 solver.allocate(nBasis_);
536 solver.computeLU(tempU);
537 solver.solve(tempv, tempcoeffs);
538
539 // Transfer solution to full-sized member variable
540 for (int i = 0; i < nBasis_; ++i) {
541 coeffs_[i] = tempcoeffs[i];
542 }
543
544 } else
545 if (nBasis_ == maxHist_) {
546
547 LuSolver solver;
548 solver.allocate(maxHist_);
549 solver.computeLU(U_);
550 solver.solve(v_, coeffs_);
551
552 }
553
554 // Flip the sign of the coeffs_ vector (see comment above)
555 for (int i = 0; i < nBasis_; ++i) {
556 coeffs_[i] *= -1.0;
557 }
558
559 return;
560 }
561
562 template <class Iterator, class T>
563 void AmIteratorTmpl<Iterator,T>::updateTrial()
564 {
565
566 // Set state and residual trial vectors to current values
567 setEqual(stateTrial_, stateHistory_[0]);
568 setEqual(residualTrial_, residualHistory_[0]);
569
570 // Add linear combinations of state and residual basis vectors
571 if (nBasis_ > 0) {
572
573 // Combine basis vectors into trial guess and predicted residual
574 addEqVectors(stateTrial_, stateBasis_, coeffs_);
575 addEqVectors(residualTrial_, residualBasis_, coeffs_);
576
577 }
578
579 #ifdef PSCF_AM_TEST
580 // Additional direct computation of error after projection step
581 if (hasAmTest_){
582 timerOmega_.stop();
583
584 // Additional MDE solution
585 timerMDE_.start();
586 update(stateTrial_);
587 evaluate();
588 timerMDE_.stop();
589
590 // Residual computation
591 timerResid_.start();
592 getResidual(temp_);
593 timerResid_.stop();
594
595 // Compute error after projection
596 timerError_.start();
597 projectionError_ = computeError(temp_, stateTrial_, errorType_, 0);
598 timerError_.stop();
599 timerOmega_.start();
600 }
601 #endif
602
603 }
604
605 // Private virtual member functions
606
607 /*
608 * Compute ramped mixing parameter for Anderson mixing algorithm.
609 */
610 template <class Iterator, class T>
612 {
613 if (useLambdaRamp_ && (nBasis_ < maxHist_)) {
614 double factor = 1.0 - pow(r_, nBasis_ + 1);
615 return factor*lambda_;
616 } else {
617 return lambda_;
618 }
619 }
620
621 /*
622 * Update entire U matrix.
623 */
624 template <class Iterator, class T>
625 void
627 DMatrix<double> & U,
628 RingBuffer<T> const & residualBasis)
629 {
630 int nBasis = residualBasis.size();
631 int maxHist = U.capacity1();
632 UTIL_CHECK(maxHist >= nBasis);
633
634 // Update matrix U by shifting elements diagonally
635 for (int m = maxHist - 1; m > 0; --m) {
636 for (int n = maxHist-1; n > 0; --n) {
637 U(m,n) = U(m-1,n-1);
638 }
639 }
640
641 // Compute U matrix's new row 0 and col 0
642 for (int m = 0; m < nBasis; ++m) {
643 double dotprod = dotProduct(residualBasis[0],residualBasis[m]);
644 if (m == 0) {
645 U(0,0) = dotprod;
646 } else {
647 U(m,0) = dotprod;
648 U(0,m) = dotprod;
649 }
650 }
651
652 }
653
654 /*
655 * Compute v vector (dot products of residual and basis vectors).
656 */
657 template <class Iterator, class T>
658 void AmIteratorTmpl<Iterator, T>::computeV(
659 DArray<double> & v,
660 T const & resCurrent,
661 RingBuffer<T> const & residualBasis)
662 {
663 int nBasis = residualBasis.size();
664 UTIL_CHECK(v.capacity() >= nBasis);
665 for (int m = 0; m < nBasis; ++m) {
666 v[m] = dotProduct(resCurrent, residualBasis[m]);
667 }
668 }
669
670 /*
671 * Compute scalar error, possibly output to log.
672 */
673 template <class Iterator, class T>
674 double
676 T&stateTrial,
677 std::string errorType,
678 int verbose)
679 {
680 double error = 0.0;
681
682 // Compute L2 norm of the residual vector
683 double normRes = norm(residTrial);
684
685 // Check if calculation has diverged (normRes will be NaN)
686 if (std::isnan(normRes)) {
687 throw NanException("AmIteratorTmpl::computeError",
688 __FILE__, __LINE__);
689 // Catch in solve method, which breaks the iteration loop
690 }
691
692 if (verbose < 2) {
693
694 // Set error value
695 if (errorType == "maxResid") {
696 error = maxAbs(residTrial);
697 } else if (errorType == "normResid") {
698 error = normRes;
699 } else if (errorType == "rmsResid") {
700 error = normRes/sqrt(nElements());
701 } else if (errorType == "relNormResid") {
702 double normField = norm(stateTrial);
703 error = normRes/normField;
704 } else {
705 UTIL_THROW("Invalid iterator error type in parameter file.");
706 }
707
708 } else {
709
710 // Find max residual vector element
711 double maxRes = maxAbs(residTrial);
712
713 // Find root-mean-squared residual element value
714 double rmsRes = normRes/sqrt(nElements());
715
716 // Find norm of residual vector relative to state
717 double normField = norm(stateTrial);
718 double relNormRes = normRes/normField;
719
720 // Set error value
721 if (errorType == "maxResid") {
722 error = maxRes;
723 } else if (errorType == "normResid") {
724 error = normRes;
725 } else if (errorType == "rmsResid") {
726 error = rmsRes;
727 } else if (errorType == "relNormResid") {
728 error = relNormRes;
729 } else {
730 UTIL_THROW("Invalid iterator error type in parameter file.");
731 }
732
733 Log::file() << "\n";
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";
737 Log::file() << "Relative Norm = " << Dbl(relNormRes,15)
738 << std::endl;
739 }
740
741 return error;
742 }
743
744 /*
745 * Compute error (use current residual, errorType).
746 */
747 template <class Iterator, class T>
749 {
750 return computeError(residualHistory_[0], stateHistory_[0],
752 }
753
754 /*
755 * Update a list of basis vectors.
756 */
757 template <class Iterator, class T>
758 void
759 AmIteratorTmpl<Iterator,T>::updateBasis(RingBuffer<T> & basis,
760 RingBuffer<T> const & history)
761 {
762 // Make sure at least two histories are stored
763 UTIL_CHECK(history.size() >= 2);
764
765 // Set up array to store new basis
766 basis.advance();
767 if (basis[0].isAllocated()) {
768 UTIL_CHECK(basis[0].capacity() == history[0].capacity());
769 } else {
770 basis[0].allocate(history[0].capacity());
771 }
772
773 // New basis vector is difference between two most recent vectors
774 subVV(basis[0], history[0], history[1]);
775 }
776
777 /*
778 * Add a linear combination of basis vectors to a vector v.
779 */
780 template <class Iterator, class T>
781 void
782 AmIteratorTmpl<Iterator,T>::addEqVectors(T& v,
783 RingBuffer<T> const & basis,
784 DArray<double> coeffs)
785 {
786 int nBasis = basis.size();
787 UTIL_CHECK(coeffs.capacity() >= nBasis);
788 for (int i = 0; i < nBasis; i++) {
789 addEqVc(v, basis[i], coeffs[i]);
790 }
791 }
792
793 /*
794 * Add a correction based on the predicted remaining residual.
795 */
796 template <class Iterator, class T>
797 void
798 AmIteratorTmpl<Iterator,T>::addCorrection(T& stateTrial,
799 T const & residualTrial)
800 {
801 double lambda = computeLambda();
802 addEqVc(stateTrial, residualTrial, lambda);
803 }
804
805 // Private virtual vector math functions
806
807 /*
808 * Compute L2 norm of a vector.
809 */
810 template <class Iterator, class T>
811 double AmIteratorTmpl<Iterator,T>::norm(T const & a)
812 {
813 double normSq = dotProduct(a, a);
814 return sqrt(normSq);
815 }
816
817 /*
818 * Vector assignment, a = b .
819 */
820 template <class Iterator, class T>
821 void AmIteratorTmpl<Iterator,T>::setEqual(T& a, T const & b)
822 { VecOp::eqV(a, b); }
823
824 /*
825 * Compute and return the inner product of two vectors
826 */
827 template <class Iterator, class T>
828 double
829 AmIteratorTmpl<Iterator,T>::dotProduct(T const & a, T const & b)
830 { return Reduce::innerProduct(a, b); }
831
832 /*
833 * Compute and return the maximum magnitude element of a vector.
834 */
835 template <class Iterator, class T>
836 double AmIteratorTmpl<Iterator,T>::maxAbs(T const & a)
837 { return Reduce::maxAbs(a); }
838
839 /*
840 * Compute the vector difference a = b - c .
841 */
842 template <class Iterator, class T>
843 void AmIteratorTmpl<Iterator,T>::subVV(T& a, T const & b, T const & c)
844 { VecOp::subVV(a, b, c); }
845
846 /*
847 * Composite a += b*c for vectors a and b, scalar c .
848 */
849 template <class Iterator, class T>
850 void AmIteratorTmpl<Iterator,T>::addEqVc(T& a, T const & b, double c)
851 { VecOp::addEqVc(a, b, c); }
852
853}
854#endif
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.
Definition LuSolver.h:31
void allocate(int n)
Allocate memory.
Definition LuSolver.cpp:146
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.
Definition Array.h:250
Dynamically allocatable contiguous array template.
Definition DArray.h:32
void allocate(int capacity)
Allocate the underlying C array.
Definition DArray.h:262
Dynamically allocated Matrix.
Definition DMatrix.h:25
void allocate(int capacity1, int capacity2)
Allocate memory for a matrix.
Definition DMatrix.h:170
Dbl()
Default constructor.
Definition Dbl.cpp:17
Int()
Default constructor.
Definition Int.cpp:19
static std::ostream & file()
Get log ostream by reference.
Definition Log.cpp:59
int capacity1() const
Get number of rows (range of the first array index).
Definition Matrix.h:132
void setClassName(const char *className)
Set class name string.
Class for storing history of previous values in an array.
Definition RingBuffer.h:27
void allocate(int capacity)
Allocate a new empty buffer.
Definition RingBuffer.h:257
void clear()
Set previously allocated buffer to empty state.
Definition RingBuffer.h:274
int capacity() const
Return the capacity of the buffer.
Definition RingBuffer.h:333
void advance()
Advances the pointer to an added element without assigning a value.
Definition RingBuffer.h:306
int size() const
Return number of values currently in the buffer.
Definition RingBuffer.h:325
#define UTIL_CHECK(condition)
Assertion macro suitable for serial or parallel production code.
Definition global.h:68
#define UTIL_THROW(msg)
Macro for throwing an Exception, reporting function, file and line number.
Definition global.h:49
double innerProduct(Array< double > const &a, Array< double > const &b)
Compute Euclidean inner product of two real arrays .
Definition Reduce.cpp:176
double maxAbs(Array< double > const &in)
Get maximum absolute magnitude of array elements .
Definition Reduce.cpp:260
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).
Definition VecOp.cpp:26
void subVV(Array< double > &a, Array< double > const &b, Array< double > const &c)
Vector-vector subtraction, a[i] = b[i] - c[i] (real).
Definition VecOp.cpp:100
void addEqVc(Array< double > &a, Array< double > const &b, const double c)
Add scaled vector in-place, a[i] += b[i]*c (real).
Definition VecOp.cpp:400
PSCF package top-level namespace.