PSCF v1.5.0
McSimulator.tpp
1#ifndef RP_MC_SIMULATOR_TPP
2#define RP_MC_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 "McSimulator.h"
12
13#include <rp/fts/montecarlo/McMove.h>
14#include <rp/fts/montecarlo/McMoveFactory.h>
15#include <rp/fts/montecarlo/McMoveManager.h>
16
17#include <rp/fts/analyzer/Analyzer.h>
18#include <rp/fts/analyzer/AnalyzerFactory.h>
19#include <rp/fts/analyzer/AnalyzerManager.h>
20#include <rp/fts/trajectory/TrajectoryReaderFactory.h>
21#include <rp/fts/trajectory/TrajectoryReader.h>
22#include <rp/fts/perturbation/Perturbation.h>
23#include <rp/fts/ramp/Ramp.h>
24
25#include <rp/fts/simulator/Simulator.h>
26#include <rp/fts/simulator/SimState.h>
27#include <rp/fts/compressor/Compressor.h>
28#include <rp/system/System.h>
29#include <rp/field/WFields.h>
30#include <rp/field/CFields.h>
31
32#include <pscf/field/RField.h>
33
34#include <util/param/Factory.h>
35#include <util/param/ParamComposite.h>
36#include <util/random/Random.h>
37#include <util/misc/Timer.h>
38
39#include <gsl/gsl_eigen.h>
40
41namespace Pscf {
42namespace Rp {
43
44 using namespace Util;
45
46 /*
47 * Constructor.
48 */
49 template <int D, class T>
51 : Simulator<D,T>(system),
52 mcMoveManagerPtr_(nullptr),
53 analyzerManagerPtr_(nullptr),
54 trajectoryReaderFactoryPtr_(nullptr)
55 {
56 ParamComposite::setClassName("McSimulator");
57 mcMoveManagerPtr_
58 = new McMoveManager<D,T>(*this, system),
59 analyzerManagerPtr_
60 = new AnalyzerManager<D,T>(*this, system),
61 trajectoryReaderFactoryPtr_
64 }
65
66 /*
67 * Destructor.
68 */
69 template <int D, class T>
71 {
72 delete mcMoveManagerPtr_;
73 delete analyzerManagerPtr_;
74 if (trajectoryReaderFactoryPtr_) {
75 delete trajectoryReaderFactoryPtr_;
76 }
77 }
78
79 /*
80 * Read parameter file block.
81 */
82 template <int D, class T>
83 void McSimulator<D,T>::readParameters(std::istream &in)
84 {
85 // Optionally read random seed. Initialize random number generators
87
88 // Optionally read McMoveManager block
90
91 // Optionally read Compressor block
92 bool isEnd = false;
94 if (hasMcMoves()) {
96 }
98 // A Compressor is required if MC moves are declared.
99 // A Ramp is allowed only if MC moves are declared.
100
101 // Optionally read Perturbation and/or Ramp blocks
103 if (hasMcMoves()) {
104 Simulator<D,T>::readRamp(in, isEnd);
105 }
106
107 // Optionally read AnalyzerManager block
108 Analyzer<D,T>::baseInterval = 0; // default value
109 ParamComposite::readParamCompositeOptional(in, analyzerManager());
110
111 // Figure out what needs to be saved in stored state
112 state().needsCc = false;
113 state().needsDc = false;
114 state().needsHamiltonian = true;
115 if (mcMoveManager().needsCc()){
116 state().needsCc = true;
117 }
119 state().needsDc = true;
120 }
121
122 // Allocate memory for Simulator<D,T> base class
124 }
125
126 /*
127 * Initialize just prior to a run.
128 */
129 template <int D, class T>
130 void McSimulator<D,T>::setup(int nStep, bool isSimulation)
131 {
132 UTIL_CHECK((Simulator<D,T>::system().w().hasData()));
133
134 // Eigenanalysis of the projected chi matrix.
136
139 }
140
142 Simulator<D,T>::ramp().setup(nStep);
143 }
144
145 // Solve the MDE and compute c-fields for the initial state
146 Simulator<D,T>::system().compute();
147
148 // Compress the initial state (adjust pressure-like field)
149 if (isSimulation && Simulator<D,T>::hasCompressor()) {
150 int status = Simulator<D,T>::compressor().compress();
151 if (status != 0) {
152 UTIL_THROW("Initial compression failed");
153 }
154 Simulator<D,T>::compressor().clearTimers();
155 }
156
157 // Compute field components and Hamiltonian
159 if (state().needsCc || state().needsDc) {
161 }
162 if (state().needsDc) {
164 }
166
167 // Setup MC moves (if any)
168 if (isSimulation && hasMcMoves()) {
169 mcMoveManager().setup();
170 }
171
172 // Setup analyzers (if any)
173 if (analyzerManager().size() > 0){
174 analyzerManager().setup();
175 }
176
177 }
178
179 /*
180 * Perform a field theoretic MC simulation of nStep steps.
181 */
182 template <int D, class T>
184 {
187
188 // Initial setup
189 setup(nStep, true);
190 iStep_ = 0;
192 Simulator<D,T>::ramp().setParameters(iStep_);
193 }
194 int analyzerBaseInterval = Analyzer<D,T>::baseInterval;
195 Log::file() << std::endl;
196
197 // Start timer
198 Timer timer;
199 timer.start();
200
201 // Analyze initial step
202 Timer analyzerTimer;
203 analyzerTimer.start();
204 if (analyzerBaseInterval != 0) {
205 if (analyzerManager().size() > 0) {
206 analyzerManager().sample(iStep_);
207 }
208 }
209 analyzerTimer.stop();
210
211 // Main Monte Carlo loop
212 for (iTotalStep_ = 0; iTotalStep_ < nStep; ++iTotalStep_) {
213
214 // Choose and attempt an McMove
215 bool converged;
216 converged = mcMoveManager().chooseMove().move();
217
218 if (converged){
219 iStep_++;
220
222 Simulator<D,T>::ramp().setParameters(iStep_);
223 }
224
225 // Analysis (if any)
226 analyzerTimer.start();
227 if (analyzerBaseInterval != 0) {
228 if (analyzerManager().size() > 0) {
229 if (iStep_ % analyzerBaseInterval == 0) {
230 analyzerManager().sample(iStep_);
231 }
232 }
233 }
234 analyzerTimer.stop();
235
236 } else{
237 Log::file() << "Step: "<< iTotalStep_
238 << " failed to converge" << "\n";
239 }
240 }
241
242 // A rejected move or a failed step restores w, but not the c
243 // fields, propagators and block concentrations, which still hold
244 // the rejected trial solution. Recompute them for the final w.
245 if (!Simulator<D,T>::system().c().hasData()) {
246 Simulator<D,T>::system().compute();
247 }
248
249 timer.stop();
250 double time = timer.time();
251 double analyzerTime = analyzerTimer.time();
252
253 // Output move statistics and final analysis results
254 mcMoveManager().output();
255 if (analyzerBaseInterval != 0){
256 analyzerManager().output();
257 }
258
259 // Final output from ramp (if any)
261 Simulator<D,T>::ramp().output();
262 }
263
264 // Output times for the simulation run
265 Log::file() << std::endl;
266 Log::file() << "nStep " << nStep << std::endl;
267 if (iStep_ != nStep){
268 Log::file() << "nFail Step "
269 << (nStep - iStep_) << std::endl;
270 }
271 Log::file() << "Total run time " << time
272 << " sec" << std::endl;
273 double rStep = double(nStep);
274 Log::file() << "time / nStep " << time / rStep
275 << " sec" << std::endl;
276 Log::file() << "Analyzer run time " << analyzerTime
277 << " sec" << std::endl;
278 Log::file() << std::endl;
279
280 // Output number of times MDE has been solved for the simulation run
282
283 // Print McMove acceptance statistics
284 long attempt;
285 long accept;
286 long fail;
287 using namespace std;
288 Log::file() << "Move Statistics:" << endl << endl;
289 Log::file() << setw(20) << left << "Move Name"
290 << setw(10) << right << "Attempted"
291 << setw(10) << right << "Accepted"
292 << setw(13) << right << "AcceptRate"
293 << setw(10) << right << "Failed"
294 << setw(13) << right << "FailRate"
295 << endl;
296 int nMove = mcMoveManager().size();
297 for (int iMove = 0; iMove < nMove; ++iMove) {
298 attempt = mcMoveManager()[iMove].nAttempt();
299 accept = mcMoveManager()[iMove].nAccept();
300 fail = mcMoveManager()[iMove].nFail();
301 Log::file() << setw(20) << left
302 << mcMoveManager()[iMove].className()
303 << setw(10) << right << attempt
304 << setw(10) << accept
305 << setw(13) << fixed << setprecision(5)
306 << ( attempt == 0 ? 0.0 : double(accept)/double(attempt) )
307 << setw(10) << fail
308 << setw(13) << fixed << setprecision(5)
309 << ( attempt == 0 ? 0.0 : double(fail)/double(attempt) )
310 << endl;
311 }
312 Log::file() << endl;
313
314 }
315
316 /*
317 * Open, read and analyze a trajectory file
318 */
319 template <int D, class T>
320 void McSimulator<D,T>::analyze(int min, int max,
321 std::string classname,
322 std::string filename)
323 {
324 // Preconditions
325 UTIL_CHECK(min >= 0);
326 UTIL_CHECK(max >= min);
328 UTIL_CHECK(analyzerManager().size() > 0);
329
330 // Construct TrajectoryReader
331 TrajectoryReader<D,T>* trajectoryReaderPtr;
332 trajectoryReaderPtr = trajectoryReaderFactory().factory(classname);
333 if (!trajectoryReaderPtr) {
334 std::string message;
335 message = "Invalid TrajectoryReader class name " + classname;
336 UTIL_THROW(message.c_str());
337 }
338
339 // Open trajectory file
340 trajectoryReaderPtr->open(filename);
341 trajectoryReaderPtr->readHeader();
342
343 // Main loop over trajectory frames. A frame is read only if its
344 // index is at most max, so that the system is left with frame max
345 // and any frames after max are never read.
346 Timer timer;
347 timer.start();
348 iStep_ = 0;
349 while (iStep_ <= max && trajectoryReaderPtr->readFrame()) {
351
352 // Initialize analyzers
353 if (iStep_ == min) {
354 setup(0, false);
355 }
356
357 // Sample property values only for iStep >= min, at multiples
358 // of the analyzer base interval (as in a simulation)
359 if (iStep_ >= min && iStep_ % Analyzer<D,T>::baseInterval == 0) {
360 analyzerManager().sample(iStep_);
361 }
362
363 ++iStep_;
364 }
365 timer.stop();
366 Log::file() << "end main loop" << std::endl;
367 int nFrame = iStep_ - min;
368 trajectoryReaderPtr->close();
369 delete trajectoryReaderPtr;
370 UTIL_CHECK(nFrame > 0);
371
372 // Output results of all analyzers to output files
373 analyzerManager().output();
374
375 // Output number of frames and times
376 Log::file() << std::endl;
377 Log::file() << "# of frames " << nFrame << std::endl;
378 Log::file() << "run time " << timer.time()
379 << " sec" << std::endl;
380 Log::file() << "time / frame " << timer.time()/double(nFrame)
381 << " sec" << std::endl;
382 Log::file() << std::endl;
383
384 }
385
386 /*
387 * Output McMoveManager timer results.
388 */
389 template <int D, class T>
390 void McSimulator<D,T>::outputTimers(std::ostream& out) const
391 {
393 Simulator<D,T>::compressor().outputTimers(out);
394 }
395 out << "\n";
396 out << "MC move time contributions:\n";
397 mcMoveManager().outputTimers(out);
398 }
399
400 /*
401 * Clear all McMoveManager timers.
402 */
403 template <int D, class T>
405 { mcMoveManager().clearTimers(); }
406
407}
408}
409#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
McMoveManager(McSimulator< D, T > &simulator, System< D, T > &system)
Constructor.
AnalyzerManager< D, T > const & analyzerManager() const
Get the AnalyzerManager (const).
virtual void clearTimers()
Clear timers.
virtual void readParameters(std::istream &in)
Read parameter file block.
McMoveManager< D, T > const & mcMoveManager() const
Get the McMoveManager (const).
virtual void analyze(int min, int max, std::string classname, std::string filename)
Read and analyze a trajectory file.
bool hasMcMoves() const
Have any MC moves been defined?
virtual void outputTimers(std::ostream &out) const
Output timing results.
~McSimulator()
Destructor.
void simulate(int nStep)
Perform a field theoretic Monte-Carlo simulation.
Factory< TrajectoryReader< D, T > > & trajectoryReaderFactory()
Get the trajectory reader factory by reference.
McSimulator(System< D, T > &system)
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.
virtual void outputMdeCounter(std::ostream &out) const
Output MDE counter.
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, CPT > & state()
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.
static std::ostream & file()
Get log ostream by reference.
Definition Log.cpp:59
void setClassName(const char *className)
Set 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.