PSCF v1.5.0
Sweep.tpp
1#ifndef RP_SWEEP_TPP
2#define RP_SWEEP_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 "Sweep.h" // class template header
12
13#include <rp/scft/iterator/Iterator.h>
14#include <rp/scft/ScftThermo.h>
15#include <rp/system/System.h>
16#include <rp/solvers/Mixture.h>
17#include <rp/field/Domain.h>
18#include <rp/field/WFields.h>
19#include <rp/field/CFields.h>
20#include <rp/environment/Environment.h>
21
22#include <pscf/crystal/Basis.h>
23#include <pscf/crystal/UnitCell.h>
24
25#include <pscf/interaction/Interaction.h>
26
27#include <util/misc/FileMaster.h>
28#include <util/misc/ioUtil.h>
29
30#include <pscf/sweep/SweepTmpl.tpp> // base class template implementation
31
32namespace Pscf {
33namespace Rp {
34
35 using namespace Util;
36
37 // Maximum number of previous states = order of continuation + 1
38 #define RP_HISTORY_CAPACITY 3
39
40 /*
41 * Default constructor (for unit testing).
42 */
43 template <int D, class T>
45 : SweepTmplT(RP_HISTORY_CAPACITY),
46 writeCRGrid_(false),
47 writeCBasis_(false),
48 writeWRGrid_(false),
49 systemPtr_(nullptr)
50 {}
51
52 /*
53 * Constructor, creates association with parent system.
54 */
55 template <int D, class T>
57 : SweepTmplT(RP_HISTORY_CAPACITY),
58 writeCRGrid_(false),
59 writeCBasis_(false),
60 writeWRGrid_(false),
61 systemPtr_(&sys)
62 {
63 // Get specialized sweep parameters from Environment
64 if (system().hasEnvironment()) {
66 system().environment().getParameterTypes());
67 }
68 }
69
70 /*
71 * Destructor.
72 */
73 template <int D, class T>
75 {}
76
77 /*
78 * Set association with a parent system (for unit testing).
79 */
80 template <int D, class T>
82 { systemPtr_ = &system; }
83
84 /*
85 * Read parameters.
86 */
87 template <int D, class T>
88 void Sweep<D,T>::readParameters(std::istream& in)
89 {
90 // Call the base class's readParameters function.
92
93 // Read optional flags indicating which field types to output
97 }
98
99 /*
100 * Check allocation of one state object, allocate if necessary.
101 */
102 template <int D, class T>
104 {
107 state.allocate();
108 state.unitCell() = system().domain().unitCell();
109 }
110
111 /*
112 * Setup operations at the beginning of a sweep.
113 */
114 template <int D, class T>
116 {
117 // Precondition - require a symmetric iterator
118 UTIL_CHECK(system().iterator().isSymmetric());
119
120 // Initialize base class sub-object
122 checkAllocation(trial_);
123
124 // Open log summary file
125 std::string fileName = SweepTmplT::baseFileName_;
126 fileName += "sweep.log";
127 system().fileMaster().openOutputFile(fileName, logFile_);
128 logFile_ << " step ds free_energy pressure"
129 << std::endl;
130 };
131
132 /*
133 * Set non-adjustable system parameters to new values.
134 *
135 * \param s path length coordinate, in range [0,1]
136 */
137 template <int D, class T>
140 // Empty default implementation allows Sweep<D> to be compiled.
141 UTIL_THROW("Calling unimplemented function Sweep::setParameters");
142 };
143
144 /*
145 * Create guess for adjustable variables by polynomial extrapolation.
146 */
147 template <int D, class T>
148 void Sweep<D,T>::extrapolate(double sNew)
149 {
152
153 // If historySize == 1, do nothing: Use previous system state
154 // as trial for the new state.
155
156 if (historySize > 1) {
158
159 // Does the iterator allow a flexible unit cell ?
160 bool isFlexible = system().iterator().isFlexible();
161
162 // Compute coefficients of polynomial extrapolation to sNew
164
165 // Set extrapolated trial w fields
166 double coeff;
167 int nMonomer = system().mixture().nMonomer();
168 int nBasis = system().domain().basis().nBasis();
169 DArray<double>* newFieldPtr;
170 DArray<double>* oldFieldPtr;
171 int i, j, k;
172 for (i=0; i < nMonomer; ++i) {
173 newFieldPtr = &(trial_.field(i));
174
175 // Previous state k = 0 (most recent)
176 oldFieldPtr = &SweepTmplT::state(0).field(i);
177 coeff = SweepTmplT::c(0);
178 for (j=0; j < nBasis; ++j) {
179 (*newFieldPtr)[j] = coeff*(*oldFieldPtr)[j];
180 }
181
182 // Previous states k >= 1 (older)
183 for (k = 1; k < historySize; ++k) {
184 oldFieldPtr = &SweepTmplT::state(k).field(i);
185 coeff = SweepTmplT::c(k);
186 for (j=0; j < nBasis; ++j) {
187 (*newFieldPtr)[j] += coeff*(*oldFieldPtr)[j];
188 }
189 }
190 }
191
192 // Make sure unitCellParameters_ is up to date with system
193 // (if we are sweeping in a lattice parameter, then the system
194 // parameters will be up-to-date but unitCellParameters_ wont be)
195 FSArray<double, 6> systemParameters
196 = system().domain().unitCell().parameters();
197 unitCellParameters_ = systemParameters;
198
199 // If isFlexible, extrapolate the flexible unit cell parameters
200 if (isFlexible) {
201
202 double coeff;
203 double parameter;
204 const FSArray<bool,6> flexParams
205 = system().iterator().flexibleParams();
206 const int nParameter
207 = system().domain().unitCell().nParameter();
208 UTIL_CHECK(flexParams.size() == nParameter);
209
210 // Add contributions from all previous states
211 for (k = 0; k < historySize; ++k) {
212 coeff = SweepTmplT::c(k);
213 for (int i = 0; i < nParameter; ++i) {
214 if (flexParams[i]) {
215 if (k == 0) {
216 unitCellParameters_[i] = 0.0;
217 }
218 parameter
219 = SweepTmplT::state(k).unitCell().parameter(i);
220 unitCellParameters_[i] += coeff*parameter;
221 }
222 }
223 }
224
225 }
226
227 // Reset trial_.unitCell() object
228 trial_.unitCell().setParameters(unitCellParameters_);
229
230 // Check if any trial unit cell parameter differs from the
231 // corresponding parameter of the system
232 bool newCellParams(false);
233 for (int i = 0; i < systemParameters.size(); i++) {
234 if (fabs(systemParameters[i] - unitCellParameters_[i]) >= 1e-10) {
235 newCellParams = true;
236 break;
237 }
238 }
239
240 // Transfer data from trial_ state to parent system
241 trial_.setSystemState(newCellParams);
242 }
243
244 };
245
246 /*
247 * Call current iterator to solve SCFT problem.
248 *
249 * Return 0 for sucessful solution, 1 on failure to converge.
250 */
251 template <int D, class T>
252 int Sweep<D,T>::solve(bool isContinuation)
253 { return system().iterate(isContinuation); };
254
255 /*
256 * Reset system to previous solution after iterature failure.
257 *
258 * The implementation of this function should reset the system state
259 * to correspond to that stored in state(0).
260 */
261 template <int D, class T>
263 {
264 bool isFlexible = system().iterator().isFlexible();
265 SweepTmplT::state(0).setSystemState(isFlexible);
266 }
267
268 /*
269 * Update state(0) and output data after successful convergence
270 *
271 * The implementation of this function should copy the current
272 * system state into state(0) and output any desired information
273 * about the current converged solution.
274 */
275 template <int D, class T>
277 {
278 SweepTmplT::state(0).setSystem(system());
279 SweepTmplT::state(0).getSystemState();
280
281 // Output converged solution to several files
282 outputSolution();
283
284 // Output summary to log file
285 outputSummary(logFile_);
286
287 };
288
289 template <int D, class T>
290 void Sweep<D,T>::outputSolution()
291 {
292 std::ofstream out;
293 std::string outFileName;
294 std::string indexString = toString(SweepTmplT::nAccept() - 1);
295
296 // Open parameter file, with thermodynamic properties at end
297 outFileName = SweepTmplT::baseFileName_;
298 outFileName += indexString;
299 outFileName += ".stt";
300 system().fileMaster().openOutputFile(outFileName, out);
301
302 // Write data file, with thermodynamic properties at end
303 system().writeParamNoSweep(out);
304 out << std::endl;
305 system().scft().write(out);
306 out.close();
307
308 // Write w fields
309 UTIL_CHECK(system().w().hasData());
310 outFileName = SweepTmplT::baseFileName_;
311 outFileName += indexString;
312 outFileName += "_w";
313 if (system().w().isSymmetric()) {
314 outFileName += ".bf";
315 system().w().writeBasis(outFileName);
316 } else {
317 outFileName += ".rf";
318 system().w().writeRGrid(outFileName);
319 }
320
321 // Optionally write c rgrid files
322 if (writeCRGrid_) {
323 UTIL_CHECK(system().c().hasData());
324 outFileName = SweepTmplT::baseFileName_;
325 outFileName += indexString;
326 outFileName += "_c";
327 outFileName += ".rf";
328 system().c().writeRGrid(outFileName);
329 }
330
331 // Optionally write c basis files
332 if (writeCBasis_ && system().c().isSymmetric()) {
333 UTIL_CHECK(system().c().hasData());
334 outFileName = SweepTmplT::baseFileName_;
335 outFileName += indexString;
336 outFileName += "_c";
337 outFileName += ".bf";
338 system().c().writeBasis(outFileName);
339 }
340
341 // Optionally write w rgrid files
342 if (writeWRGrid_ && system().w().isSymmetric()) {
343 outFileName = SweepTmplT::baseFileName_;
344 outFileName += indexString;
345 outFileName += "_w";
346 outFileName += ".rf";
347 system().w().writeRGrid(outFileName);
348 }
349
350 }
351
352 template <int D, class T>
353 void Sweep<D,T>::outputSummary(std::ostream& out)
354 {
355 int i = SweepTmplT::nAccept() - 1;
356 double sNew = SweepTmplT::s(0);
357 if (!system().scft().hasData()) system().scft().compute();
358 out << Int(i,5) << Dbl(sNew)
359 << Dbl(system().scft().fHelmholtz(),16)
360 << Dbl(system().scft().pressure(),16);
361 out << std::endl;
362 }
363
364 template <int D, class T>
366 { logFile_.close(); }
367
368} // namespace Rp
369} // namespace Pscf
370#endif
void setSystem(ST &system)
Set association with System, after default construction.
Definition FieldState.h:233
FieldState for fields in symmetry-adapted basis format.
void allocate()
Allocate all fields.
const UnitCell< D > & unitCell() const
Get UnitCell (i.e., lattice type and parameters) by const reference.
bool writeWRGrid_
Should converged w fields be written to file in r-grid format?
Sweep()
Default constructor.
Definition Sweep.tpp:44
virtual void setup()
Setup operation at the beginning of a sweep.
Definition Sweep.tpp:115
bool hasSystem()
Does an association with the parent system exist?
virtual void getSolution()
Update state(0) and output data after successful convergence.
Definition Sweep.tpp:276
bool writeCRGrid_
Should concentration fields be written to file in r-grid format?
virtual void cleanup()
Cleanup operation at the beginning of a sweep.
Definition Sweep.tpp:365
virtual int solve(bool isContinuation)
Call current iterator to solve SCFT problem.
Definition Sweep.tpp:252
virtual void setParameters(double sNew)=0
Set system parameters to new values.
Definition Sweep.tpp:138
void setSystem(System< D, T > &system)
Set association with parent system.
Definition Sweep.tpp:81
virtual void checkAllocation(BasisFieldState< D, T > &state)
Check allocation of fields in one state, allocate if necessary.
Definition Sweep.tpp:103
System< D, T > & system()
Return the parent system by reference.
virtual void readParameters(std::istream &in)
Read parameters from param file.
Definition Sweep.tpp:88
bool writeCBasis_
Should concentration fields be written to file in basis format?
virtual void extrapolate(double sNew)
Create a guess for adjustable variables by continuation.
Definition Sweep.tpp:148
virtual void reset()
Reset system to previous solution after iterature failure.
Definition Sweep.tpp:262
~Sweep()
Destructor.
Definition Sweep.tpp:74
Base class template for classes that represent a complete system.
void addParameterTypes(GArray< ParameterType > paramTypes)
BasisFieldState< D, T > & state(int i)
Definition SweepTmpl.h:107
virtual void readParameters(std::istream &in)
Definition SweepTmpl.tpp:42
Dynamically allocatable contiguous array template.
Definition DArray.h:32
Dbl()
Default constructor.
Definition Dbl.cpp:17
A fixed capacity (static) contiguous array with a variable logical size.
Definition FSArray.h:38
int size() const
Return logical size of this array (i.e., number of elements).
Definition FSArray.h:210
Int()
Default constructor.
Definition Int.cpp:19
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
std::string toString(int n)
Return string representation of an integer.
Definition ioUtil.cpp:52
Code for programs that simulate real-valued periodic fields.
Definition param_pc.dox:2
PSCF package top-level namespace.