PSCF v1.5.0
SweepTmpl.tpp
1#ifndef PSCF_SWEEP_TMPL_TPP
2#define PSCF_SWEEP_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 "SweepTmpl.h"
12#include <util/misc/Log.h>
13
14namespace Pscf {
15
16 using namespace Util;
17
18 /*
19 * Constructor
20 */
21 template <class State>
23 : ns_(0),
25 historyCapacity_(historyCapacity),
26 historySize_(0),
27 nAccept_(0),
28 reuseState_(true)
29 { setClassName("SweepTmpl"); }
30
31 /*
32 * Destructor.
33 */
34 template <class State>
37
38 /*
39 * Read parameters.
40 */
41 template <class State>
42 void SweepTmpl<State>::readParameters(std::istream& in)
43 {
44 // Default values
45 baseFileName_ = "";
46
47 // Read parameters
48 read<int>(in, "ns", ns_);
49 if (ns_ <= 0) {
50 UTIL_THROW("Sweep parameter ns (number of steps) must be "
51 "positive");
52 }
53 readOptional<std::string>(in, "baseFileName", baseFileName_);
54 readOptional<int>(in, "historyCapacity", historyCapacity_);
55 if (historyCapacity_ <= 0) {
56 UTIL_THROW("Sweep parameter historyCapacity must be positive");
57 }
58 readOptional<bool>(in, "reuseState", reuseState_);
59
60 // Allocate required arrays
61 states_.allocate(historyCapacity_);
62 stateHistory_.allocate(historyCapacity_);
63 sHistory_.allocate(historyCapacity_);
64 c_.allocate(historyCapacity_);
65 }
66
67 template <class State>
69 {
70
71 // Compute and output ds
72 double ds = 1.0/double(ns_);
73 double ds0 = ds;
74 Log::file() << std::endl;
75 Log::file() << "ns = " << ns_ << std::endl;
76 Log::file() << "ds = " << ds << std::endl;
77
78 // Initial setup, before a sweep
79 setup();
80
81 // The contour variable is s = k/den for integers k and den. The
82 // step ds = 1/den starts at 1/ns, and is halved on backtracking
83 // by doubling den and k. Computing s from these integers, rather
84 // than by repeated addition of ds, puts every state at an exact
85 // multiple of ds, and the last state at exactly s = 1.
86 long k = 0;
87 long den = ns_;
88
89 // Solve for initial state of sweep
90 double sNew = 0.0;
91 Log::file() << std::endl;
92 Log::file() << "===========================================\n";
93 Log::file() << "Attempt s = " << sNew << std::endl;
94
95 int error;
96 bool isContinuation = false; // False on first step
97 error = solve(isContinuation);
99 if (error) {
100 UTIL_THROW("Failure to converge initial state of sweep");
101 } else {
102 accept(sNew);
103 }
104
105 // Loop over states on path
106 bool finished = false; // Are we finished with the loop?
107 while (!finished) {
108
109 // Loop over iteration attempts, with decreasing ds as needed
110 error = 1;
111 while (error) {
112
113 // Set a new contour variable value sNew = s(0) + ds
114 sNew = double(k + 1)/double(den);
115 Log::file() << std::endl;
116 Log::file() << "===========================================\n";
117 Log::file() << "Attempt s = " << sNew << std::endl;
118
119 // Set non-adjustable system parameters to new values
120 setParameters(sNew);
121
122 // Guess new state variables by polynomial extrapolation.
123 // This function must both compute the extrapolation and
124 // set initial guess values in the parent system.
125 extrapolate(sNew);
126
127 // Attempt iterative SCFT solution
128 isContinuation = reuseState_;
129 error = solve(isContinuation);
130
131 // Process success or failure
132 if (error) {
133 Log::file() << "Backtrack and halve sweep step size:"
134 << std::endl;
135
136 // Upon failure, reset state to last converged solution
137 reset();
138
139 // Decrease ds by half
140 ds *= 0.50;
141 den *= 2;
142 k *= 2;
143 if (ds < 0.1*ds0) {
144 UTIL_THROW("Sweep decreased ds too many times.");
145 }
146
147 } else {
148
149 // Upon successful convergence, update history and nAccept
150 accept(sNew);
151 ++k;
152
153 }
154 }
155 if (k >= den) {
156 finished = true;
157 }
158 }
159 Log::file() << "===========================================\n";
160
161 // Clean up after end of the entire sweep
162 cleanup();
163
164 }
165
166 template <class State>
167 void SweepTmpl<State>::addParameterType(std::string name, int nId,
168 ParameterModifier& modifier)
169 {
170 // Check if parameterTypes_ already has an element with this name
171 if (parameterTypes_.size() > 0) {
172 for (int i = 0; i < parameterTypes_.size(); ++i) {
173 UTIL_CHECK(parameterTypes_[i].name != name);
174 }
175 }
176
177 ParameterType paramType;
178 paramType.name = name;
179 paramType.nId = nId;
180 paramType.modifierPtr = &modifier;
181 parameterTypes_.append(paramType);
182 }
183
184 template <class State>
187 // Check if parameterTypes_ already has an element with this name
188 if (parameterTypes_.size() > 0) {
189 for (int i = 0; i < parameterTypes_.size(); ++i) {
190 UTIL_CHECK(parameterTypes_[i].name != paramType.name);
191 }
192 }
193
194 parameterTypes_.append(paramType);
195 }
196
197 template <class State>
199 {
200 for (int i = 0; i < paramTypes.size(); i++) {
201 // Check if parameterTypes_ already has an element with this name
202 if (parameterTypes_.size() > 0) {
203 for (int j = 0; j < parameterTypes_.size(); j++) {
204 UTIL_CHECK(parameterTypes_[j].name != paramTypes[i].name);
205 }
206 }
207
208 parameterTypes_.append(paramTypes[i]);
209 }
210 }
211
212 /*
213 * Initialize history variables (must be called by setup function).
214 */
215 template <class State>
217 {
218 UTIL_CHECK(historyCapacity_ > 0);
219 UTIL_CHECK(states_.capacity() == historyCapacity_);
220 UTIL_CHECK(sHistory_.capacity() == historyCapacity_);
221 UTIL_CHECK(stateHistory_.capacity() == historyCapacity_);
222
223 // Check allocation of all states, allocate if necessary
224 for (int i = 0; i < historyCapacity_; ++i) {
225 checkAllocation(states_[i]);
226 }
227
228 // Set pointers in stateHistory_ to refer to objects in array states_
229 nAccept_ = 0;
230 historySize_ = 0;
231 for (int i = 0; i < historyCapacity_; ++i) {
232 sHistory_[i] = 0.0;
233 stateHistory_[i] = &states_[i];
234 }
235 }
236
237 template <class State>
238 void SweepTmpl<State>::accept(double sNew)
239 {
240
241 // Shift elements of sHistory_
242 for (int i = historyCapacity_ - 1; i > 0; --i) {
243 sHistory_[i] = sHistory_[i-1];
244 }
245 sHistory_[0] = sNew;
246
247 // Shift elements of stateHistory_ (pointers to stored solutions)
248 State* temp;
249 temp = stateHistory_[historyCapacity_-1];
250 for (int i = historyCapacity_ - 1; i > 0; --i) {
251 stateHistory_[i] = stateHistory_[i-1];
252 }
253 stateHistory_[0] = temp;
254
255 // Update counters nAccept_ and historySize_
256 ++nAccept_;
257 if (historySize_ < historyCapacity_) {
258 ++historySize_;
259 }
260
261 // Call getSolution to copy system state to state(0).
262 getSolution();
263 }
264
265 /*
266 * Use Lagrange polynomials to compute coefficients for continuation.
267 */
268 template <class State>
270 {
271 UTIL_CHECK(historySize_ <= historyCapacity_);
272 if (historySize_ == 1) {
273 c_[0] = 1.0;
274 } else {
275 double num, den;
276 int i, j;
277 for (i = 0; i < historySize_; ++i) {
278 num = 1.0;
279 den = 1.0;
280 for (j = 0; j < historySize_; ++j) {
281 if (j != i) {
282 num *= (sNew - s(j));
283 den *= (s(i) - s(j));
284 }
285 }
286 c_[i] = num/den;
287 }
288 }
289 // Theory: The coefficient c_[i] is a Lagrange polynomial
290 // function c_[i](sNew) of sNew that is defined such that
291 // c_[i](s(i)) = 1 and c_[i](s(j)) = 0 for any j != i.
292 // Given a set of values y(i) previously obtained at contour
293 // variable values s(i) for all 0 <= i < historySize_, a
294 // linear combination f(sNew) = \sum_i c_[i](sNew)*y(i) summed
295 // over i = 0, ..., historySize_ - 1 gives a polynomial in
296 // sNew that passes through all previous values, such that
297 // f(sNew) = y(i) for sNew = s(i).
298 }
299
300 /*
301 * Clean up after the end of a sweep (empty default implementation).
302 */
303 template <class State>
306
307} // namespace Pscf
308#endif
Base class allowing subclasses to define sweepable parameters.
void addParameterTypes(GArray< ParameterType > paramTypes)
Declare an array of specialized sweep parameter types.
~SweepTmpl()
Destructor.
Definition SweepTmpl.tpp:35
virtual void checkAllocation(State &state)=0
Check allocation of one state, allocate if necessary.
std::string baseFileName_
Base name for output files.
Definition SweepTmpl.h:297
virtual void cleanup()
Clean up operation at the end of a sweep.
void initialize()
Initialize variables that track history of solutions.
SweepTmpl(int historyCapacity)
Constructor (protected).
Definition SweepTmpl.tpp:22
void setCoefficients(double sNew)
Compute coefficients of previous states for continuation.
void addParameterType(std::string name, int nId, ParameterModifier &modifier)
Declare a specialized parameter type.
virtual void sweep()
Iterate to solution.
Definition SweepTmpl.tpp:68
virtual int solve(bool isContinuation)=0
int ns_
Number of steps.
Definition SweepTmpl.h:294
virtual void readParameters(std::istream &in)
Read ns and baseFileName parameters.
Definition SweepTmpl.tpp:42
GArray< ParameterType > parameterTypes_
Array of specialized parameter types.
Definition SweepTmpl.h:311
double s(int i) const
Get the value of s for a stored solution, with i = 0 most recent.
Definition SweepTmpl.h:122
int historyCapacity() const
Get the maximum number of stored previous states.
Definition SweepTmpl.h:168
An automatically growable array, analogous to a std::vector.
Definition GArray.h:34
int size() const
Return the logical size of this array (number of elements).
Definition GArray.h:450
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.
#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
PSCF package top-level namespace.
Declaration of a specialized sweep parameter type.