PSCF v1.5.0
BdSimulator.tpp
1#ifndef RP_BD_SIMULATOR_TPP
2#define RP_BD_SIMULATOR_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 <rp/fts/brownian/BdSimulator.h>
12
13#include <rp/fts/brownian/BdStep.h>
14#include <rp/fts/brownian/BdStepFactory.h>
15
16#include <rp/fts/simulator/Simulator.h>
17#include <rp/fts/analyzer/AnalyzerManager.h>
18#include <rp/fts/analyzer/AnalyzerFactory.h>
19#include <rp/fts/trajectory/TrajectoryReader.h>
20#include <rp/fts/trajectory/TrajectoryReaderFactory.h>
21#include <rp/fts/perturbation/Perturbation.h>
22#include <rp/fts/ramp/Ramp.h>
23#include <rp/fts/compressor/Compressor.h>
24#include <rp/system/System.h>
25#include <rp/solvers/Mixture.h>
26#include <rp/field/Domain.h>
27#include <rp/field/CFields.h>
28#include <rp/field/WFields.h>
29
30#include <pscf/field/RField.h>
31
32#include <util/param/Factory.h>
33#include <util/param/ParamComposite.h>
34#include <util/random/Random.h>
35#include <util/misc/Timer.h>
36
37namespace Pscf {
38namespace Rp {
39
40 using namespace Util;
41
42 /*
43 * Constructor.
44 */
45 template <int D, class T>
47 : Simulator<D,T>(system),
48 analyzerManagerPtr_(nullptr),
49 bdStepPtr_(nullptr),
50 bdStepFactoryPtr_(nullptr),
51 trajectoryReaderFactoryPtr_(nullptr)
52 {
53 ParamComposite::setClassName("BdSimulator");
54 analyzerManagerPtr_
55 = new AnalyzerManager<D,T>(*this, system),
56 bdStepFactoryPtr_ = new BdStepFactory<D,T>(*this);
57 trajectoryReaderFactoryPtr_
60 }
61
62 /*
63 * Destructor.
64 */
65 template <int D, class T>
67 {
68 // Created in constructor
69 if (analyzerManagerPtr_) {
70 delete analyzerManagerPtr_;
71 }
72 if (bdStepFactoryPtr_) {
73 delete bdStepFactoryPtr_;
74 }
75 if (trajectoryReaderFactoryPtr_) {
76 delete trajectoryReaderFactoryPtr_;
77 }
78
79 // Created in readParameters function
80 if (bdStepPtr_) {
81 delete bdStepPtr_;
82 }
83
84 // Note: There is no pointer member variable that points to a
85 // TrajectoryReader<D,T> because an instance of this class is
86 // both created and destroyed within the analyze member function.
87 }
88
89 /*
90 * Read parameter file block for a BD simulator.
91 */
92 template <int D, class T>
93 void BdSimulator<D,T>::readParameters(std::istream &in)
94 {
95 // Optionally read random seed, initialize random number generators
97
98 // Optionally read a BdStep block
99 bool isEnd = false;
100 std::string className;
102 UTIL_CHECK(bdStepFactoryPtr_);
103 bdStepPtr_ =
104 bdStepFactoryPtr_->readObjectOptional(in, *this,
105 className, isEnd);
106 if (!hasBdStep() && ParamComponent::echo()) {
108 << " BdStep{ [absent] }\n";
109 }
110
111 // Compressor is required if a BdStep exists
112 // A Ramp is allowed only if a BdStep exists
113
114 // Optionally read a Compressor block
116 if (hasBdStep()) {
118 }
119
120 // Optionally read a Perturbation block
122
123 // Optionally read a Ramp block
124 if (hasBdStep()) {
125 Simulator<D,T>::readRamp(in, isEnd);
126 }
127
128 // Optionally read an AnalyzerManager block
129 Analyzer<D,T>::baseInterval = 0; // default value
131
132 // Figure out what variables need to be saved in stored state()
133 state().needsCc = false;
134 state().needsDc = false;
135 state().needsHamiltonian = false;
136 if (hasBdStep()) {
137 if (bdStep().needsCc()){
138 state().needsCc = true;
139 }
140 if (bdStep().needsDc()){
141 state().needsDc = true;
142 }
143 }
144
145 // Allocate memory for Simulator<D,T> base class
147 }
148
149 /*
150 * Setup before main loop of a simulate or analyze command.
151 */
152 template <int D, class T>
153 void BdSimulator<D,T>::setup(int nStep, bool isSimulation)
154 {
155 UTIL_CHECK((Simulator<D,T>::system().w().hasData()));
156
157 // Eigenanalysis of the projected chi matrix.
159
162 }
163
165 Simulator<D,T>::ramp().setup(nStep);
166 }
167
168 // Solve MDE and compute c-fields for the intial state
169 Simulator<D,T>::system().compute();
170
171 // Compress the initial state (adjust pressure-like field)
173 if (isSimulation) {
174 int status = Simulator<D,T>::compressor().compress();
175 if (status != 0) {
176 UTIL_THROW("Initial compression failed");
177 }
178 }
179 Simulator<D,T>::compressor().clearTimers();
180 }
181
182 // Compute field components and Hamiltonian for initial state.
187
188 if (isSimulation && hasBdStep()) {
189 bdStep().setup();
190 }
191
192 if (analyzerManager().size() > 0){
193 analyzerManager().setup();
194 }
195
196 }
197
198 /*
199 * Perform a field theoretic MC simulation of nStep steps.
200 */
201 template <int D, class T>
203 {
206 UTIL_CHECK((Simulator<D,T>::system().w().hasData()));
207
208 // Initial setup
209 setup(nStep, true);
210 iStep_ = 0;
212 Simulator<D,T>::ramp().setParameters(iStep_);
213 }
214 int analyzerBaseInterval = Analyzer<D,T>::baseInterval;
215
216 // Start timer
217 Timer timer;
218 timer.start();
219
220 // Analysis for initial state (if any)
221 Timer analyzerTimer;
222 analyzerTimer.start();
223 if (analyzerBaseInterval != 0) {
224 if (analyzerManager().size() > 0) {
225 analyzerManager().sample(iStep_);
226 }
227 }
228 analyzerTimer.stop();
229
230 // Main simulation loop
231 for (iTotalStep_ = 0; iTotalStep_ < nStep; ++iTotalStep_) {
232
233 // Take a step (modifies W fields, then applies compressor)
234 bool converged;
235 converged = bdStep().step();
236
237 // Accept step iff compressor converged
238 if (converged){
239 iStep_++;
240
242 Simulator<D,T>::ramp().setParameters(iStep_);
243 }
244
245 // Analysis (if any)
246 analyzerTimer.start();
247 if (analyzerBaseInterval != 0) {
248 if (analyzerManager().size() > 0) {
249 if (iStep_ % analyzerBaseInterval == 0) {
250 analyzerManager().sample(iStep_);
251 }
252 }
253 }
254 analyzerTimer.stop();
255
256 } else {
257 Log::file() << "Step: "<< iTotalStep_
258 << " failed to converge" << "\n";
259 }
260
261 }
262
263 // A failed step restores w, but not the c fields, propagators and
264 // block concentrations, which still hold the failed trial solution.
265 // Recompute them for the final w.
266 if (!Simulator<D,T>::system().c().hasData()) {
267 Simulator<D,T>::system().compute();
268 }
269
270 timer.stop();
271 double time = timer.time();
272 double analyzerTime = analyzerTimer.time();
273
274 // Output final analyzer results
275 if (analyzerBaseInterval != 0){
276 analyzerManager().output();
277 }
278
279 // Output results of ramp
281 Log::file() << std::endl;
282 Simulator<D,T>::ramp().output();
283 }
284
285 // Output times for the simulation run
286 Log::file() << std::endl;
287 Log::file() << "nStep " << nStep << std::endl;
288 if (iStep_ != nStep){
289 Log::file() << "nFail Step " << (nStep - iStep_)
290 << std::endl;
291 }
292 Log::file() << "Total run time " << time
293 << " sec" << std::endl;
294 double rStep = double(nStep);
295 Log::file() << "time / nStep " << time / rStep
296 << " sec" << std::endl;
297 Log::file() << "Analyzer run time " << analyzerTime
298 << " sec" << std::endl;
299 Log::file() << std::endl;
300
301 // Output number of times MDE has been solved for the simulation run
302 Log::file() << "MDE counter "
303 << Simulator<D,T>::compressor().mdeCounter() << std::endl;
304 Log::file() << std::endl;
305
306 }
307
308 /*
309 * Open, read and analyze a trajectory file
310 */
311 template <int D, class T>
313 int max,
314 std::string classname,
315 std::string filename)
316 {
317 // Preconditions
318 UTIL_CHECK(min >= 0);
319 UTIL_CHECK(max >= min);
321 UTIL_CHECK(analyzerManager().size() > 0);
322
323 // Construct a TrajectoryReader
324 TrajectoryReader<D,T>* trajectoryReaderPtr;
325 trajectoryReaderPtr = trajectoryReaderFactory().factory(classname);
326 if (!trajectoryReaderPtr) {
327 std::string message;
328 message = "Invalid TrajectoryReader class name " + classname;
329 UTIL_THROW(message.c_str());
330 }
331
332 // Open trajectory file
333 trajectoryReaderPtr->open(filename);
334 trajectoryReaderPtr->readHeader();
335
336 // Main loop over trajectory frames. A frame is read only if its
337 // index is at most max, so that the system is left with frame max
338 // and any frames after max are never read.
339 Timer timer;
340 timer.start();
341 iStep_ = 0;
342 while (iStep_ <= max && trajectoryReaderPtr->readFrame()) {
344
345 // Initial setup of analyzers
346 if (iStep_ == min) {
347 setup(0, false);
348 }
349
350 // Sample property values only for iStep >= min, at multiples
351 // of the analyzer base interval (as in a simulation)
352 if (iStep_ >= min && iStep_ % Analyzer<D,T>::baseInterval == 0) {
353 analyzerManager().sample(iStep_);
354 }
355
356 ++iStep_;
357 }
358 timer.stop();
359 Log::file() << "end main loop" << std::endl;
360 int nFrame = iStep_ - min;
361 trajectoryReaderPtr->close();
362 delete trajectoryReaderPtr;
363 UTIL_CHECK(nFrame > 0);
364
365 // Output results of all analyzers to output files
366 analyzerManager().output();
367
368 // Output number of frames and times
369 Log::file() << std::endl;
370 Log::file() << "# of frames " << nFrame << std::endl;
371 Log::file() << "run time " << timer.time()
372 << " sec" << std::endl;
373 Log::file() << "time / frame " << timer.time()/double(nFrame)
374 << " sec" << std::endl;
375 Log::file() << std::endl;
376
377 }
378
379 /*
380 * Get the TrajectoryReader factory.
381 */
382 template <int D, class T>
385 {
386 UTIL_CHECK(trajectoryReaderFactoryPtr_);
387 return *trajectoryReaderFactoryPtr_;
388 }
389
390}
391}
392#endif
AnalyzerManager(Simulator< D, T > &simulator, System< D, T > &system)
Constructor.
static void initStatic()
Define and initialize baseInterval (initialized to 1).
Definition Analyzer.tpp:22
static long baseInterval
The interval for every Analyzer must be a multiple of baseInterval.
Definition Analyzer.h:125
virtual void readParameters(std::istream &in)
Read parameter file block.
AnalyzerManager< D, T > & analyzerManager()
Get the AnalyzerManager (const).
BdStep< D, T > & bdStep()
Get the BdStep by non-const reference.
~BdSimulator()
Destructor.
virtual void analyze(int min, int max, std::string classname, std::string filename)
Read and analyze a trajectory file.
BdSimulator(System< D, T > &system)
Constructor.
bool hasBdStep() const
Does this BdSimulator have a BdStep object?
void simulate(int nStep)
Perform a field theoretic Brownian dynamics (BD) simulation.
Factory< TrajectoryReader< D, T > > & trajectoryReaderFactory()
Get the trajectory reader factory by reference.
BdStepFactory(BdSimulator< D, T > &simulator)
Constructor.
Simulator(System< D, T > &system)
Constructor.
Definition Simulator.tpp:53
void computeHamiltonian()
Compute the Hamiltonian used in PS-FTS.
void readRamp(std::istream &in, bool &isEnd)
Optionally read a Ramp parameter file block.
void clearData()
Clear field eigen-components and Hamiltonian components.
void readPerturbation(std::istream &in, bool &isEnd)
Optionally read a Perturbation parameter file block.
void computeWc()
Compute eigenvector components of the current w fields.
void readCompressor(std::istream &in, bool &isEnd)
Optionally read a Compressor parameter file block.
void computeCc()
Compute eigenvector components of the current c fields.
System< D, T > & system()
Get the parent system by reference.
Definition Simulator.h:944
void allocate()
Allocate required memory during initialization.
void readRandomSeed(std::istream &in)
Optionally read a random seed and initialize RNGs.
Perturbation< D, T > const & perturbation() const
Get a Perturbation by const reference.
Definition Simulator.h:994
void computeDc()
Compute functional derivatives of the Hamiltonian.
long iTotalStep_
Step counter - total number of attempted BD or MC steps.
Definition Simulator.h:811
bool hasPerturbation() const
Does this Simulator have a Perturbation?
Definition Simulator.h:989
bool hasRamp() const
Does this Simulator have a Ramp?
Definition Simulator.h:1010
SimState< D, T > & state()
Get the SimState stored internal state by reference.
Definition Simulator.h:1031
bool hasCompressor() const
Does this Simulator have a Compressor?
Definition Simulator.h:968
Compressor< D, T > const & compressor() const
Get the Compressor by const reference.
Definition Simulator.h:981
long iStep_
Step counter - number of steps for which the compressor converged.
Definition Simulator.h:806
void analyzeChi()
Perform eigenvalue analysis of projected chi matrix.
Ramp< D, T > const & ramp() const
Get a Ramp by const reference.
Definition Simulator.h:1015
Base class template for classes that represent a complete system.
Factory for subclasses of TrajectoryReader.
Trajectory file reader (abstract base class).
virtual void open(std::string filename)=0
Open trajectory file and allocate memory if necessary.
virtual void readHeader()
Read header of trajectory file (if any).
virtual void close()=0
Close the trajectory file.
Factory template.
Definition Factory.h:34
static std::ostream & file()
Get log ostream by reference.
Definition Log.cpp:59
std::string indent() const
Return indent string for this object (string of spaces).
static bool echo()
Get echo parameter.
void setClassName(const char *className)
Set class name string.
std::string className() const
Get class name string.
void readParamCompositeOptional(std::istream &in, ParamComposite &child, bool next=true)
Add and attempt to read an optional child ParamComposite.
Wall clock timer.
Definition Timer.h:35
void start(TimePoint begin)
Start timing from an externally supplied time.
Definition Timer.cpp:49
double time() const
Return the accumulated time, in seconds.
Definition Timer.cpp:37
void stop(TimePoint end)
Stop the clock at an externally supplied time.
Definition Timer.cpp:73
#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
Code for programs that simulate real-valued periodic fields.
Definition param_pc.dox:2
PSCF package top-level namespace.