PSCF v1.5.0
NrIterator.cpp
1/*
2* PSCF - Polymer Self-Consistent Field
3*
4* Copyright 2015 - 2026, David Morse (morse012@um.edu) and co-authors
5* Distributed under the terms of the GNU General Public License.
6*/
7
8#include "NrIterator.h"
9#include <r1/system/System.h>
10#include <r1/solvers/Mixture.h>
11#include <r1/solvers/Polymer.h>
12#include <r1/solvers/Solvent.h>
13#include <pscf/interaction/Interaction.h>
14#include <pscf/chem/Ensemble.h>
15#include <util/misc/Log.h>
16
17#include <math.h>
18#include <cmath>
19#include <limits>
20
21namespace Pscf {
22namespace R1
23{
24
25 using namespace Util;
26
28 : Iterator(),
29 epsilon_(0.0),
30 maxItr_(0),
31 isAllocated_(false),
32 newJacobian_(false),
33 needsJacobian_(true),
34 isCanonical_(true)
35 { setClassName("NrIterator"); }
36
39 epsilon_(0.0),
40 maxItr_(0),
41 isAllocated_(false),
42 newJacobian_(false),
43 needsJacobian_(true),
44 isCanonical_(true)
45 { setClassName("NrIterator"); }
46
49
50 void NrIterator::readParameters(std::istream& in)
51 {
52 maxItr_ = 400;
53 read(in, "epsilon", epsilon_);
54 readOptional(in, "maxItr", maxItr_);
55 setup();
56 }
57
58 void NrIterator::setup()
59 {
60 int nm = system().mixture().nMonomer(); // number of monomer types
61 int nx = domain().nx(); // number of grid points
62 UTIL_CHECK(nm > 0);
63 UTIL_CHECK(nx > 0);
64 int nr = nm*nx; // number of residual components
65 if (isAllocated_) {
66 UTIL_CHECK(cArray_.capacity() == nm);
67 UTIL_CHECK(residual_.capacity() == nr);
68 } else {
69 cArray_.allocate(nm);
70 wArray_.allocate(nm);
71 residual_.allocate(nr);
72 jacobian_.allocate(nr, nr);
73 residualNew_.allocate(nr);
74 dOmega_.allocate(nr);
75 wFieldsNew_.allocate(nm);
76 cFieldsNew_.allocate(nm);
77 for (int i = 0; i < nm; ++i) {
78 wFieldsNew_[i].allocate(nx);
79 cFieldsNew_[i].allocate(nx);
80 }
81 solver_.allocate(nr);
82 isAllocated_ = true;
83 }
84 }
85
86 void NrIterator::computeResidual(Array<FieldT> const & wFields,
87 Array<FieldT> const & cFields,
88 Array<double>& residual)
89 {
90 DMatrix<double> const & chi = system().interaction().chi();
91 int nm = system().mixture().nMonomer(); // number of monomer types
92 int nx = domain().nx(); // number of grid points
93 int i; // grid point index
94 int j, k; // monomer indices
95 int ir; // residual index
96
97 // Loop over grid points
98 for (i = 0; i < nx; ++i) {
99
100 // Copy volume fractions at grid point i to cArray_
101 for (j = 0; j < nm; ++j) {
102 cArray_[j] = cFields[j][i];
103 }
104
105 // Compute w fields, without Langrange multiplier, from c fields
106 //system().interaction().computeW(cArray_, wArray_);
107 for (j = 0; j < nm; ++j) {
108 wArray_[j] = 0.0;
109 for (k = 0; k < nm; ++k) {
110 wArray_[j] += chi(j, k)*cArray_[k];
111 }
112 }
113
114 // Initial residual = wPredicted(from above) - actual w
115 for (j = 0; j < nm; ++j) {
116 ir = j*nx + i;
117 residual[ir] = wArray_[j] - wFields[j][i];
118 }
119
120 // Residuals j = 1, ..., nm-1 are differences from component j=0
121 for (j = 1; j < nm; ++j) {
122 ir = j*nx + i;
123 residual[ir] = residual[ir] - residual[i];
124 }
125
126 // Residual for component j=0 then imposes incompressiblity
127 residual[i] = -1.0;
128 for (j = 0; j < nm; ++j) {
129 residual[i] += cArray_[j];
130 }
131 }
132
133 /*
134 * Note: In canonical ensemble, the spatial integral of the
135 * incompressiblity residual is guaranteed to be zero, as a result of how
136 * volume fractions are computed in SCFT. One of the nx incompressibility
137 * constraints is thus redundant. To avoid this redundancy, replace the
138 * incompressibility residual at the last grid point by a residual that
139 * requires the w field for the last monomer type at the last grid point
140 * to equal zero.
141 */
142
143 if (isCanonical_) {
144 residual[nx-1] = wFields[nm-1][nx-1];
145 }
146
147 }
148
149 /*
150 * Compute Jacobian matrix numerically, by evaluating finite differences.
151 */
152 void NrIterator::computeJacobian()
153 {
154 int nm = system().mixture().nMonomer(); // number of monomer types
155 int nx = domain().nx(); // number of grid points
156 int i; // monomer index
157 int j; // grid point index
158
159 // Copy system().wFields to wFieldsNew.
160 for (i = 0; i < nm; ++i) {
161 for (j = 0; j < nx; ++j) {
162 UTIL_CHECK(nx == wFieldsNew_[i].capacity());
163 UTIL_CHECK(nx == system().wField(i).capacity());
164 wFieldsNew_[i][j] = system().wField(i)[j];
165 }
166 }
167
168 // Compute jacobian, column by column
169 double delta = 0.001;
170 int nr = nm*nx; // number of residual elements
171 int jr; // jacobian row index
172 int jc = 0; // jacobian column index
173 for (i = 0; i < nm; ++i) {
174 for (j = 0; j < nx; ++j) {
175 wFieldsNew_[i][j] += delta;
176 system().mixture().compute(wFieldsNew_, cFieldsNew_);
177 computeResidual(wFieldsNew_, cFieldsNew_, residualNew_);
178 for (jr = 0; jr < nr; ++jr) {
179 jacobian_(jr, jc) =
180 (residualNew_[jr] - residual_[jr])/delta;
181 }
182 wFieldsNew_[i][j] = system().wField(i)[j];
183 ++jc;
184 }
185 }
186
187 // Decompose Jacobian matrix
188 solver_.computeLU(jacobian_);
189
190 }
191
192 void NrIterator::incrementWFields(Array<FieldT> const & wOld,
193 Array<double> const & dW,
194 Array<FieldT> & wNew)
195 {
196 int nm = system().mixture().nMonomer(); // number of monomers types
197 int nx = domain().nx(); // number of grid points
198 int i; // monomer index
199 int j; // grid point index
200 int k = 0; // residual element index
201
202 // Add dW
203 for (i = 0; i < nm; ++i) {
204 for (j = 0; j < nx; ++j) {
205 wNew[i][j] = wOld[i][j] - dW[k];
206 ++k;
207 }
208 }
209
210 // If canonical, shift such that last element is exactly zero
211 if (isCanonical_) {
212 double shift = wNew[nm-1][nx-1];
213 for (i = 0; i < nm; ++i) {
214 for (j = 0; j < nx; ++j) {
215 wNew[i][j] -= shift;
216 }
217 }
218 }
219
220 }
221
222 double NrIterator::residualNorm(Array<double> const & residual) const
223 {
224 int nm = system().mixture().nMonomer(); // number of monomer types
225 int nx = domain().nx(); // number of grid points
226 int nr = nm*nx; // number of residual components
227 double value, norm;
228 norm = 0.0;
229 for (int ir = 0; ir < nr; ++ir) {
230 value = fabs(residual[ir]);
231 // A NaN element fails every comparison, and would be skipped.
232 // Return infinity, so that a residual that is not finite is
233 // never accepted as an improvement or as converged.
234 if (!std::isfinite(value)) {
235 return std::numeric_limits<double>::infinity();
236 }
237 if (value > norm) {
238 norm = value;
239 }
240 }
241 return norm;
242 }
243
244 int NrIterator::solve(bool isContinuation)
245 {
246 int nm = system().mixture().nMonomer(); // number of monomer types
247 int np = system().mixture().nPolymer(); // number of polymer species
248 int ns = system().mixture().nSolvent(); // number of solvent species
249 int nx = domain().nx(); // number of grid points
250 int nr = nm*nx; // number of residual elements
251
252 // Determine if isCanonical (iff all species ensembles are closed)
253 isCanonical_ = true;
254 Ensemble ensemble;
255 for (int i = 0; i < np; ++i) {
256 ensemble = system().mixture().polymer(i).ensemble();
257 if (ensemble == Ensemble::Unknown) {
258 UTIL_THROW("Unknown species ensemble");
259 }
260 if (ensemble == Ensemble::Open) {
261 isCanonical_ = false;
262 }
263 }
264 if (ns > 0) {
265 for (int i = 0; i < ns; ++i) {
266 ensemble = system().mixture().solvent(i).ensemble();
267 if (ensemble == Ensemble::Unknown) {
268 UTIL_THROW("Unknown species ensemble");
269 }
270 if (ensemble == Ensemble::Open) {
271 isCanonical_ = false;
272 }
273 }
274 }
275
276 // If isCanonical, shift so that last element is zero.
277 // Note: This is one of the residuals in this case.
278 if (isCanonical_) {
279 double shift = wFields()[nm-1][nx-1];
280 int i, j;
281 for (i = 0; i < nm; ++i) {
282 for (j = 0; j < nx; ++j) {
283 wFields()[i][j] -= shift;
284 }
285 }
286 }
287
288 // Compute initial residual vector and norm
290 computeResidual(system().wFields(), system().cFields(), residual_);
291 double norm = residualNorm(residual_);
292 if (!std::isfinite(norm)) {
293 Log::file() << "Initial residual is not finite" << std::endl;
294 return 1;
295 }
296
297 // Set Jacobian status
298 newJacobian_ = false;
299 if (!isContinuation) {
300 needsJacobian_ = true;
301 }
302
303 // Iterative loop
304 double normNew;
305 int i, j, k;
306 for (i = 0; i < maxItr_; ++i) {
307 Log::file() << "iteration " << i
308 << " , error = " << norm
309 << std::endl;
310
311 if (norm < epsilon_) {
312 Log::file() << "Converged" << std::endl;
314 // Success
315 return 0;
316 }
317
318 if (needsJacobian_) {
319 Log::file() << "Computing jacobian" << std::endl;;
320 computeJacobian();
321 newJacobian_ = true;
322 needsJacobian_ = false;
323 }
324
325 // Compute Newton-Raphson increment dOmega_
326 solver_.solve(residual_, dOmega_);
327
328 // Try full Newton-Raphson update
329 incrementWFields(system().wFields(), dOmega_, wFieldsNew_);
330 system().mixture().compute(wFieldsNew_, cFieldsNew_);
331 computeResidual(wFieldsNew_, cFieldsNew_, residualNew_);
332 normNew = residualNorm(residualNew_);
333
334 // Decrease increment if necessary
335 j = 0;
336 while (normNew > norm && j < 3) {
337 Log::file() << " decreasing increment, error = "
338 << normNew << std::endl;
339 needsJacobian_ = true;
340 for (k = 0; k < nr; ++k) {
341 dOmega_[k] *= 0.66666666;
342 }
343 incrementWFields(system().wFields(), dOmega_, wFieldsNew_);
344 system().mixture().compute(wFieldsNew_, cFieldsNew_);
345 computeResidual(wFieldsNew_, cFieldsNew_, residualNew_);
346 normNew = residualNorm(residualNew_);
347 ++j;
348 }
349
350 // If necessary, try reversing direction
351 if (normNew > norm) {
352 Log::file() << " reversing increment, norm = "
353 << normNew << std::endl;
354 needsJacobian_ = true;
355 for (k = 0; k < nr; ++k) {
356 dOmega_[k] *= -1.000;
357 }
358 incrementWFields(system().wFields(), dOmega_, wFieldsNew_);
359 system().mixture().compute(wFieldsNew_, cFieldsNew_);
360 computeResidual(wFieldsNew_, cFieldsNew_, residualNew_);
361 normNew = residualNorm(residualNew_);
362 }
363
364 // Accept or reject update
365 if (normNew < norm) {
366
367 // Update system fields and residual vector
368 for (j = 0; j < nm; ++j) {
369 for (k = 0; k < nx; ++k) {
370 system().wField(j)[k] = wFieldsNew_[j][k];
371 system().cField(j)[k] = cFieldsNew_[j][k];
372 }
373 }
374 for (j = 0; j < nr; ++j) {
375 residual_[j] = residualNew_[j];
376 }
377 newJacobian_ = false;
378 if (!needsJacobian_) {
379 if (normNew/norm > 0.5) {
380 needsJacobian_ = true;
381 }
382 }
383 norm = normNew;
384 } else {
385 Log::file() << "Iteration failed, norm = "
386 << normNew << std::endl;
387 if (newJacobian_) {
388 return 1;
389 Log::file() << "Unrecoverable failure " << std::endl;
390 } else {
391 Log::file() << "Try rebuilding Jacobian" << std::endl;
392 needsJacobian_ = true;
393 }
394 }
395
396 }
397
398 // Failure
399 return 1;
400 }
401
402} // namespace R1
403} // namespace Pscf
int nMonomer() const
Get number of monomer types.
int nPolymer() const
Get number of polymer species.
int nSolvent() const
Get number of solvent (point particle) species.
DMatrix< double > const & chi() const
Return the chi matrix by const reference.
void allocate(int n)
Allocate memory.
Definition LuSolver.cpp:146
PolymerT & polymer(int id)
Get a polymer solver object by non-const reference.
SolventT & solvent(int id)
Get a solvent solver object.
int nx() const
Get number of spatial grid points, including both endpoints.
Iterator()
Default constructor.
void compute(DArray< FieldT > const &wFields, DArray< FieldT > &cFields)
Compute concentrations.
virtual ~NrIterator()
Destructor.
void readParameters(std::istream &in)
Read all parameters and initialize.
int solve(bool isContinuation=false)
Iterate self-consistent field equations to solution.
NrIterator()
Default constructor.
DArray< System::WField > & wFields()
Get array of all chemical potential fields.
System::WField & wField(int monomerId)
Get chemical potential field for a specific monomer type.
DArray< System::CField > & cFields()
Get array of all chemical potential fields.
const System & system() const
Get parent System by reference.
const Domain & domain() const
Get spatial domain (including grid info) by reference.
Main class in SCFT simulation of one system.
Field & cField(int monomerId)
Get chemical potential field for a specific monomer type.
Mixture & mixture()
Get Mixture by reference.
void computeFreeEnergy()
Compute free energy density and pressure for current fields.
WField & wField(int monomerId)
Get chemical potential field for a specific monomer type.
Interaction & interaction()
Get interaction (i.e., excess free energy) by reference.
Array container class template.
Definition Array.h:41
int capacity() const
Return allocated size.
Definition Array.h:250
void allocate(int capacity)
Allocate the underlying C array.
Definition DArray.h:262
void allocate(int capacity1, int capacity2)
Allocate memory for a matrix.
Definition DMatrix.h:170
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.
#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
Ensemble
Statistical ensemble for the number of molecules of one species.
Definition Ensemble.h:27
SCFT with real 1D fields.
PSCF package top-level namespace.