PSCF v1.5.0
LrCompressor.tpp
1#ifndef RP_LR_COMPRESSOR_TPP
2#define RP_LR_COMPRESSOR_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 "LrCompressor.h"
12
13#include <rp/system/System.h>
14#include <rp/solvers/Mixture.h>
15#include <rp/field/Domain.h>
16#include <rp/field/WFields.h>
17#include <rp/field/CFields.h>
18
19#include <pscf/field/FFT.h>
20#include <pscf/crystal/shiftToMinimum.h>
21
22#include <pscf/backend/Reduce.h>
23#include <pscf/backend/VecOp.h>
24#include <pscf/mesh/MeshIterator.h>
25#include <pscf/iterator/NanException.h>
26
27#include <util/format/Dbl.h>
28#include <util/global.h>
29
30namespace Pscf {
31namespace Rp {
32
33 using namespace Util;
34
35 /*
36 * Constructor.
37 */
38 template <int D, class T>
40 : Compressor<D,T>(system),
41 intra_(system),
42 errorType_("rms"),
43 epsilon_(0.0),
44 itr_(0),
45 maxItr_(100),
46 totalItr_(0),
47 verbose_(0),
48 isAllocated_(false),
49 hasIntraCorrelationK_(false)
50 { ParamComposite::setClassName("LrCompressor"); }
51
52 /*
53 * Read parameters from file.
54 */
55 template <int D, class T>
56 void LrCompressor<D,T>::readParameters(std::istream& in)
57 {
58 // Default values
59 maxItr_ = 100;
60 verbose_ = 0;
61 errorType_ = "rms";
62
63 // Read parameters
64 ParamComposite::read(in, "epsilon", epsilon_);
65 ParamComposite::readOptional(in, "maxItr", maxItr_);
66 ParamComposite::readOptional(in, "verbose", verbose_);
67 ParamComposite::readOptional(in, "errorType", errorType_);
68 }
69
70 /*
71 * Initialize just before entry to iterative loop.
72 */
73 template <int D, class T>
74 void LrCompressor<D,T>::setup()
75 {
76 IntVec<D> const & dimensions = system().domain().mesh().dimensions();
77 int kSize;
78 FFT<D,T>::computeKMesh(dimensions, kMeshDimensions_, kSize);
79
80 // Allocate memory required by AM algorithm if not done earlier.
81 if (!isAllocated_) {
82 resid_.allocate(dimensions);
83 residK_.allocate(dimensions);
84 const int nMonomer = system().mixture().nMonomer();
85 wFieldTmp_.allocate(nMonomer);
86 intraCorrelationK_.allocate(kMeshDimensions_);
87 for (int i = 0; i < nMonomer; ++i) {
88 wFieldTmp_[i].allocate(dimensions);
89 }
90 isAllocated_ = true;
91 }
92
93 }
94
95 /*
96 * Adjust pressure field to find partial saddle point.
97 */
98 template <int D, class T>
100 {
101 // Start overall timer
102 timerTotal_.start();
103
104 // Initialization and allocate operations on entry to loop.
105 setup();
106 UTIL_CHECK(isAllocated_);
107
108 // Solve MDE
109 timerMDE_.start();
110 system().compute();
112 timerMDE_.stop();
113
114 // Iterative loop
115 for (itr_ = 0; itr_ < maxItr_; ++itr_) {
116
117 if (verbose_ > 2) {
118 Log::file() << "------------------------------- \n";
119 }
120
121 if (verbose_ > 0){
122 Log::file() << " Iteration " << Int(itr_,5);
123 }
124
125 // Compute residual vector
126 computeResidual();
127
128 // Compute scalar error
129 double error;
130 try {
131 error = computeError(verbose_);
132 } catch (NanException const &) {
133 Log::file() << ", error = NaN" << std::endl;
134 break; // Exit loop if a NanException is caught
135 }
136 if (verbose_ > 0) {
137 Log::file() << ", error = " << Dbl(error, 15) << std::endl;
138 }
139
140 // Check for convergence
141 if (error < epsilon_) {
142
143 // Successful completion (i.e., converged within tolerance)
144 timerTotal_.stop();
145
146 if (verbose_ > 2) {
147 Log::file() << "-------------------------------\n";
148 }
149 if (verbose_ > 0) {
150 Log::file() << " Converged\n";
151 }
152 if (verbose_ == 2) {
153 Log::file() << "\n";
154 computeError(2);
155 }
156 totalItr_ += itr_;
157
158 return 0; // Success
159
160 } else { // if not yet converged
161
162 updateWFields();
163
164 // Solve MDE in new state
165 timerMDE_.start();
166 system().compute();
168 timerMDE_.stop();
169
170 }
171
172 }
173
174 // Failure: Iteration counter itr reached maxItr without converging
175 // or if loop breaks because of NaN error
176
177 timerTotal_.stop();
178 Log::file() << "Iterator failed to converge.\n";
179 return 1;
180 }
181
182 /*
183 * Compute and store the residual for the current system state.
184 */
185 template <int D, class T>
186 void LrCompressor<D,T>::computeResidual()
187 {
188 // Initialize resid_ to -1
189 VecOp::eqS(resid_, -1.0);
190
191 // Add all c fields
192 const int nMonomer = system().mixture().nMonomer();
193 for (int i = 0; i < nMonomer; ++i) {
194 VecOp::addEqV(resid_, system().c().rgrid(i));
195 }
196 }
197
198 /*
199 * Update system w fields using linear response approximation.
200 */
201 template <int D, class T>
202 void LrCompressor<D,T>::updateWFields()
203 {
204 // Preconditions
205 UTIL_CHECK(isAllocated_);
206 UTIL_CHECK(system().c().hasData());
207
208 // Compute intraCorrelation if necessary
209 if (!hasIntraCorrelationK_){
210 intra_.computeOmegaTotal(intraCorrelationK_);
211 hasIntraCorrelationK_ = true;
212 }
213
214 const int nMonomer = system().mixture().nMonomer();
215 const double vMonomer = system().mixture().vMonomer();
216
217 // Convert residual to Fourier Space
218 system().domain().fft().forwardTransform(resid_, residK_);
219
220 // Compute change in fields using estimated Jacobian
221 VecOp::divEqVc(residK_, intraCorrelationK_, vMonomer);
222
223 // Convert back to real space (destroys residK_)
224 system().domain().fft().inverseTransformUnsafe(residK_, resid_);
225
226 // Update new fields
227 for (int i = 0; i < nMonomer; i++) {
228 VecOp::addVV(wFieldTmp_[i], system().w().rgrid(i), resid_);
229 }
230
231 // Set system w fields
232 system().w().setRGrid(wFieldTmp_);
233 }
234
235 /*
236 * Output information to a log file (do-nothing implementation).
237 */
238 template <int D, class T>
239 void LrCompressor<D,T>::outputToLog()
240 {}
241
242 /*
243 * Mark intraCorrelationK_ as outdated.
244 */
245 template <int D, class T>
247 { hasIntraCorrelationK_ = false; }
248
249 /*
250 * Output timing information to evaluate performance.
251 */
252 template <int D, class T>
253 void LrCompressor<D,T>::outputTimers(std::ostream& out) const
254 {
255 // Output timing results, if requested.
256 double total = timerTotal_.time();
257 out << "\n";
258 out << "LrCompressor time contributions:\n";
259 out << " ";
260 out << "Total" << std::setw(22)<< "Per Iteration"
261 << std::setw(9) << "Fraction" << "\n";
262 out << "MDE solution: "
263 << Dbl(timerMDE_.time(), 9, 3) << " s, "
264 << Dbl(timerMDE_.time()/totalItr_, 9, 3) << " s, "
265 << Dbl(timerMDE_.time()/total, 9, 3) << "\n";
266 out << "\n";
267 }
268
269 /*
270 * Clear all timers.
271 */
272 template <int D, class T>
274 {
275 timerTotal_.clear();
276 timerMDE_.clear();
278 totalItr_ = 0;
279 }
280
281 /*
282 * Compute and return the scalar error.
283 */
284 template <int D, class T>
285 double LrCompressor<D,T>::computeError(int verbose)
286 {
287 double error = 0.0;
288
289 // Compute normSq error and check for NaN error
290 double normSq = Reduce::sumSq(resid_);
291 if (std::isnan(normSq)) {
292 throw NanException("LrCompressor::computeError",
293 __FILE__, __LINE__);
294 // Catch in the solve method, which breaks the iteration loop
295 }
296
297 if (verbose < 2) {
298
299 if (errorType_ == "max") {
300 error = Reduce::maxAbs(resid_);
301 } else if (errorType_ == "norm") {
302 error = sqrt(normSq);
303 } else if (errorType_ == "rms") {
304 int meshSize = system().domain().mesh().size();
305 error = sqrt(normSq/double(meshSize));
306 } else {
307 UTIL_THROW("Invalid iterator error type in parameter file.");
308 }
309
310 } else {
311
312 int meshSize = system().domain().mesh().size();
313
314 double maxRes = Reduce::maxAbs(resid_);
315 double normRes = sqrt(normSq);
316 double rmsRes = sqrt(normSq/double(meshSize));
317
318 if (errorType_ == "max") {
319 error = maxRes;
320 } else if (errorType_ == "norm") {
321 error = normRes;
322 } else if (errorType_ == "rms") {
323 error = rmsRes;
324 } else {
325 UTIL_THROW("Invalid iterator error type in parameter file.");
326 }
327
328 Log::file() << "\n";
329 Log::file() << "Max Residual = " << Dbl(maxRes,15) << "\n";
330 Log::file() << "Residual Norm = " << Dbl(normRes,15) << "\n";
331 Log::file() << "RMS Residual = " << Dbl(rmsRes,15) << "\n";
332
333 }
334 return error;
335 }
336
337}
338}
339#endif
An IntVec<D, T> is a D-component vector of elements of integer type T.
Definition IntVec.h:27
Exception thrown when not-a-number (NaN) is encountered.
NanException(const char *function, const char *file, int line, int echo=1)
Constructor.
Compressor()
Default constructor.
System< D, T > const & system() const
Return parent system by const reference.
Definition Compressor.h:128
int mdeCounter_
Count how many times MDE has been solved.
Definition Compressor.h:113
int compress() override
Iterate pressure field to obtain partial saddle point.
void outputTimers(std::ostream &out) const override
Return compressor times contributions.
void readParameters(std::istream &in) override
Read all parameters and initialize.
void clearCache() override
Mark the stored intramolecular correlation function as outdated.
void clearTimers() override
Clear all timers.
LrCompressor(System< D, T > &system)
Constructor.
Base class template for classes that represent a complete system.
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
ScalarParam< Type > & read(std::istream &in, const char *label, Type &value)
Add and read a new required ScalarParam < Type > object.
void setClassName(const char *className)
Set class name string.
ScalarParam< Type > & readOptional(std::istream &in, const char *label, Type &value)
Add and read a new optional ScalarParam < Type > object.
File containing preprocessor macros for error handling.
#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 maxAbs(Array< double > const &in)
Get maximum absolute magnitude of array elements .
Definition Reduce.cpp:260
double sumSq(Array< double > const &in)
Compute sum of of squares of array elements (real).
Definition Reduce.cpp:121
void addEqV(Array< double > &a, Array< double > const &b)
Vector-vector in-place addition, a[i] += b[i] (real).
Definition VecOp.cpp:203
void eqS(Array< double > &a, double b)
Vector assignment, a[i] = b (real).
Definition VecOp.cpp:55
void addVV(Array< double > &a, Array< double > const &b, Array< double > const &c)
Vector-vector addition, a[i] = b[i] + c[i] (real).
Definition VecOp.cpp:69
void divEqVc(Array< fftw_complex > &a, Array< double > const &b, double c)
Vector division in-place w/ coeff., a[i] /= (b[i] * c).
Definition VecOp.cpp:1214
Code for programs that simulate real-valued periodic fields.
Definition param_pc.dox:2
PSCF package top-level namespace.