Loading...
Searching...
No Matches
MonteCarlo.cpp
Go to the documentation of this file.
1/*
2** This file is part of eOn.
3**
4** SPDX-License-Identifier: BSD-3-Clause
5**
6** Copyright (c) 2010--present, eOn Development Team
7** All rights reserved.
8**
9** Repo:
10** https://github.com/TheochemUI/eOn
11*/
12#include "eon/MonteCarlo.h"
13
14#include <cmath>
15#include <stdexcept>
16
17namespace eonc {
18
19void MonteCarlo::run(int numSteps, double temperature, double stepSize) {
20 if (numSteps <= 0) {
21 throw std::invalid_argument("MonteCarlo: steps must be positive");
22 }
23 if (!(temperature > 0.0)) {
24 throw std::invalid_argument("MonteCarlo: temperature must be positive");
25 }
26 if (!(stepSize > 0.0)) {
27 throw std::invalid_argument("MonteCarlo: step_size must be positive");
28 }
29
30 if (!eonc::io::io_ok(matter->matter2con("movie.con"))) {
31 QUILL_LOG_WARNING(log, "Failed to write movie.con header frame");
32 }
33
34 const double kB = params.constants().kB;
35 int accepts = 0;
36 for (int steps = 0; steps < numSteps; ++steps) {
37 const AtomMatrix current = matter->getPositions();
38 const double ecurrent = matter->getPotentialEnergy();
39 if (!eonc::io::io_ok(matter->matter2con("movie.con", true))) {
40 QUILL_LOG_WARNING(log, "Failed to append movie.con frame");
41 }
42
43 AtomMatrix trial = current;
44 for (int i = 0; i < trial.rows(); ++i) {
45 if (matter->getFixed(i)) {
46 continue;
47 }
48 for (int j = 0; j < 3; ++j) {
49 trial(i, j) += eonc::rng::gaussRandom(0.0, stepSize);
50 }
51 }
52 matter->setPositions(trial);
53 const double etrial = matter->getPotentialEnergy();
54 const double de = etrial - ecurrent;
55 bool accept = de <= 0.0;
56 if (!accept) {
57 const double arg = -de / (kB * temperature);
58 accept = (arg >= -50.0) && (eonc::rng::randomDouble() < std::exp(arg));
59 }
60 if (accept) {
61 ++accepts;
62 } else {
63 matter->setPositions(current);
64 }
65 }
66 QUILL_LOG_INFO(log, "accepts: {}", accepts);
67}
68
69} // namespace eonc
Eigen::Matrix< double, Eigen::Dynamic, 3, eOnStorageOrder > AtomMatrix
Definition Eigen.h:37
std::shared_ptr< Matter > matter
Definition MonteCarlo.h:32
eonc::log::Scoped log
Definition MonteCarlo.h:34
const Parameters & params
Definition MonteCarlo.h:33
void run(int numSteps, double temperature, double stepSize)
constexpr bool io_ok(IoStatus s) noexcept
Definition ConFileIO.h:38
double randomDouble()
double gaussRandom(double avg, double std)
RAII resource manager for the ARTn C library with global synchronization.