Loading...
Searching...
No Matches
Dynamics.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/Dynamics.h"
13#include "eon/EonLogger.h"
14#include "eon/PathIntegral.h"
15#include "eon/Tunneling.h"
16
17#include <cmath>
18#include <stdexcept>
19
20namespace eonc {
21
22const char Dynamics::ANDERSEN[] = "andersen";
23const char Dynamics::NOSE_HOOVER[] = "nose_hoover";
24const char Dynamics::LANGEVIN[] = "langevin";
25const char Dynamics::NONE[] = "none";
26const char Dynamics::PILE[] = "pile";
27const char Dynamics::PIGLET[] = "piglet";
28
30 : matter{matter_in},
32 if (!matter) {
33 throw std::invalid_argument("Dynamics: null Matter");
34 }
35 dt = m_config.time_step;
36 nAtoms = matter->numberOfAtoms();
37 // Unfixed axes only. A partly fixed atom is not three degrees of freedom.
38 nFreeCoords = 0;
39 for (long i = 0; i < nAtoms; ++i) {
40 for (int axis = 0; axis < 3; ++axis) {
41 if (!matter->getFixed(i, axis)) {
43 }
44 }
45 }
46 temperature = m_config.temperature;
47 kB = m_config.kB;
48 vxi1 = vxi2 = xi1 = xi2 = 0.0;
49}
50
51Dynamics::~Dynamics() = default;
52
53void Dynamics::setTemperature(double temperature_in) {
54 temperature = temperature_in;
55}
56
57void Dynamics::oneStep(int stepNumber) {
58 if (m_config.thermostat_kind == ANDERSEN) {
61 } else if (m_config.thermostat_kind == NOSE_HOOVER) {
63 } else if (m_config.thermostat_kind == LANGEVIN) {
65 } else if (m_config.thermostat_kind == NONE) {
67 } else if (m_config.thermostat_kind == PILE ||
68 m_config.thermostat_kind == PIGLET) {
69 throw std::invalid_argument(
70 "path-integral dynamics is a ring-polymer trajectory, not a "
71 "velocity Verlet step");
72 }
73
74 if (stepNumber != -1) {
75 if (stepNumber == 1) {
76 QUILL_LOG_DEBUG(log, "{} {:8s} {:10s} {:12s} {:12s} {:10s}\n",
77 "[Dynamics]", "Step", "KE", "PE", "TE", "KinT");
78 }
79 double kinE = matter->getKineticEnergy();
80 double potE = matter->getPotentialEnergy();
81 const double kinT =
82 (nFreeCoords > 0 && kB > 0.0) ? 2.0 * kinE / nFreeCoords / kB : 0.0;
83
84 if (stepNumber % m_config.write_movies_interval == 0) {
85 QUILL_LOG_DEBUG(log, "{} {:8} {:10.4} {:12.4} {:12.4} {:10.2}\n",
86 "[Dynamics]", stepNumber, kinE, potE, kinE + potE, kinT);
87 }
88 }
89}
90
92 AtomMatrix positions = matter->getPositions();
93 AtomMatrix velocities = matter->getVelocities();
94 AtomMatrix accInit = matter->getAccelerations();
95
96 positions += dt * velocities + 0.5 * dt * dt * accInit;
97 matter->setPositions(positions);
98
99 AtomMatrix accFinal = matter->getAccelerations();
100 velocities += 0.5 * dt * (accInit + accFinal);
101 matter->setVelocities(velocities);
102}
103
105 auto pot = matter->getPotential();
106 if (!pot) {
107 throw std::invalid_argument("path-integral dynamics has no potential");
108 }
109 const long atoms = matter->numberOfAtoms();
110 std::vector<double> masses(static_cast<size_t>(atoms));
111 std::vector<int> numbers(static_cast<size_t>(atoms));
112 std::vector<char> free(static_cast<size_t>(3 * atoms), 1);
113 const VectorXi z = matter->getAtomicNrs();
114 for (long i = 0; i < atoms; ++i) {
115 masses[static_cast<size_t>(i)] = matter->getMass(i);
116 numbers[static_cast<size_t>(i)] = z[i];
117 for (int axis = 0; axis < 3; ++axis) {
118 if (matter->getFixed(i, axis)) {
119 free[static_cast<size_t>(3 * i + axis)] = 0;
120 }
121 }
122 }
124 opt.beads = m_config.path_beads;
126 opt.kB = kB;
128 opt.dt = dt;
129 opt.springs = m_config.path_springs == "eco" ? pathintegral::Springs::Eco
131 opt.thermostat = m_config.thermostat_kind == PIGLET
134 opt.pileTau = m_config.path_pile_tau;
135 opt.pileScale = m_config.path_pile_scale;
136 opt.ecoOmegaMax = m_config.path_eco_omega_max;
137 opt.gleFile = m_config.path_gle_file;
138 opt.seed = m_config.path_seed;
139 pathintegral::RingPolymer ring(atoms, masses, numbers, free, opt);
140 const AtomMatrix pos = matter->getPositions();
141 ring.setAllBeads(pos.data());
142 ring.thermalMomenta();
143 const Matrix3d box =
144 matter->getPeriodic() ? matter->getCell() : Matrix3d::Zero().eval();
145 // The first half of the run equilibrates; the second half averages the
146 // centroid-virial kinetic energy, the quantum kinetic energy of the
147 // N-bead ring.
148 const long equilibration = m_config.steps / 2;
149 const long production = m_config.steps - equilibration;
150 if (production > 0) {
151 const pathintegral::Sample sample =
152 ring.sample(*pot, box.data(), equilibration, production);
154 EONC_LOG_INFO("[Dynamics] ring polymer, {} beads at {:.2f} K: "
155 "centroid-virial kinetic energy {:.6f} eV over the last {} "
156 "of {} steps ({:.6f} eV classical)",
157 opt.beads, temperature, pathKineticEnergy_, production,
158 m_config.steps, 0.5 * nFreeCoords * kB * temperature);
159 }
160 const VectorXd centroid = ring.centroid();
161 const VectorXd velocity = ring.centroidVelocity();
162 AtomMatrix out = pos;
163 AtomMatrix vel = matter->getVelocities();
164 for (long i = 0; i < atoms; ++i) {
165 for (int axis = 0; axis < 3; ++axis) {
166 out(i, axis) = centroid[3 * i + axis];
167 vel(i, axis) = velocity[3 * i + axis];
168 }
169 }
170 matter->setPositions(out);
171 matter->setVelocities(vel);
172}
173
175 if (m_config.thermostat_kind == PILE || m_config.thermostat_kind == PIGLET) {
177 return;
178 }
179 double sumT = 0.0, sumT2 = 0.0;
180
182
183 if (m_config.thermostat_kind != NONE) {
184 QUILL_LOG_DEBUG(log,
185 "{} Running NVT molecular dynamics: {:8.2f} K for {} "
186 "steps ({:.4e} s)\n",
187 "[Dynamics]", temperature, m_config.steps,
188 1e-15 * m_config.time_step * m_config.timeUnit *
189 m_config.steps);
190 } else {
191 QUILL_LOG_DEBUG(log, "{} Running NVE molecular dynamics: {} steps\n",
192 "[Dynamics]", m_config.steps);
193 }
194
195 if (m_config.write_movies) {
196 if (!eonc::io::io_ok(matter->matter2con("dynamics", false))) {
197 QUILL_LOG_WARNING(log, "Failed to write dynamics movie header frame");
198 }
199 }
200
201 QUILL_LOG_DEBUG(log, "{} {:8} {:10} {:12} {:12} {:10}\n", "[Dynamics]",
202 "step", "KE", "PE", "TE", "kinT");
203
204 for (long step = 0; step < m_config.steps; step++) {
205 matter->pollCancel("dynamics");
206 oneStep();
207
208 double kinE = matter->getKineticEnergy();
209 double potE = matter->getPotentialEnergy();
210 const double kinT =
211 (nFreeCoords > 0 && kB > 0.0) ? 2.0 * kinE / nFreeCoords / kB : 0.0;
212 sumT += kinT;
213 sumT2 += kinT * kinT;
214
215 if (step % m_config.write_movies_interval == 0) {
216 QUILL_LOG_DEBUG(log, "{} {} {} {} {} {}\n", "[Dynamics]", step, kinE,
217 potE, kinE + potE, kinT);
218 }
219
220 if (m_config.write_movies && (step % m_config.write_movies_interval == 0)) {
221 if (!eonc::io::io_ok(matter->matter2con("dynamics", true))) {
222 QUILL_LOG_WARNING(log, "Failed to append dynamics movie frame");
223 }
224 }
225 }
226
227 const double nstat = static_cast<double>(std::max(m_config.steps, 1L));
228 double avgT = sumT / nstat;
229 double varT = sumT2 / nstat - avgT * avgT;
230 double stdT = std::sqrt(varT);
231 QUILL_LOG_DEBUG(log,
232 "{} Temperature : Average = {:.2f} ; StdDev = {:.2f} ; "
233 "Factor = {:.2f}\n",
234 "[Dynamics]", avgT, stdT,
235 varT / avgT / avgT * nFreeCoords / 2.0);
236}
237
239 double alpha = m_config.andersen_alpha;
240 double tCol = m_config.andersen_tcol;
241 double pCol = 1.0 - std::exp(-m_config.time_step / tCol);
242
243 AtomMatrix velocity = matter->getVelocities();
244 auto mass = matter->getMasses();
245
246 for (long i = 0; i < nAtoms; i++) {
247 if (eonc::rng::randomDouble() < pCol && !matter->getFixed(i)) {
248 for (int j = 0; j < 3; j++) {
249 double vOld = velocity(i, j);
250 const double vNew = (mass[i] > 0.0 && kB > 0.0 && temperature > 0.0)
251 ? std::sqrt(kB * temperature / mass[i]) *
252 eonc::rng::gaussRandom(0.0, 1.0)
253 : 0.0;
254 velocity(i, j) = std::sqrt(1.0 - alpha * alpha) * vOld + alpha * vNew;
255 }
256 }
257 }
258 matter->setVelocities(velocity);
259}
260
262 AtomMatrix velocity = matter->getVelocities();
263 auto mass = matter->getMasses();
264
265 for (long i = 0; i < nAtoms; i++) {
266 if (!matter->getFixed(i)) {
267 for (int j = 0; j < 3; j++) {
268 velocity(i, j) = (mass[i] > 0.0 && kB > 0.0 && temperature > 0.0)
269 ? std::sqrt(kB * temperature / mass[i]) *
270 eonc::rng::gaussRandom(0.0, 1.0)
271 : 0.0;
272 }
273 }
274 }
275 matter->setVelocities(velocity);
276}
277
279 AtomMatrix velocity = matter->getVelocities();
280 double kinE = matter->getKineticEnergy();
281 const double kinT =
282 (nFreeCoords > 0 && kB > 0.0) ? 2.0 * kinE / nFreeCoords / kB : 0.0;
283 if (!(kinT > 0.0) || !(temperature > 0.0)) {
284 return;
285 }
286 matter->setVelocities(velocity * std::sqrt(temperature / kinT));
287}
288
289void Dynamics::nhcChainHalfStep(AtomMatrix &vel, double &kinE) {
290 const double dt2 = 0.5 * dt;
291 const double dt4 = 0.25 * dt;
292 const double dt8 = 0.125 * dt;
293 const double q1 = m_config.nose_mass;
294 const double q2 = q1;
295 const double Temp = kB * temperature;
296 if (!(q1 > 0.0)) {
297 throw std::invalid_argument("thermostat.nose_mass must be positive");
298 }
299
300 // Martyna, Klein, Tuckerman JCP 97, 2635 (1992): G2 = (Q1 v_ξ1² − kT) / Q2.
301 auto g2 = [&]() { return (q1 * vxi1 * vxi1 - Temp) / q2; };
302 auto g1 = [&]() { return (2.0 * kinE - nFreeCoords * Temp) / q1; };
303
304 vxi2 += g2() * dt4;
305 vxi1 *= std::exp(-vxi2 * dt8);
306 vxi1 += g1() * dt4;
307 vxi1 *= std::exp(-vxi2 * dt8);
308 xi1 += vxi1 * dt2;
309 xi2 += vxi2 * dt2;
310 const double s = std::exp(-vxi1 * dt2);
311 vel *= s;
312 kinE *= s * s;
313 vxi1 *= std::exp(-vxi2 * dt8);
314 vxi1 += g1() * dt4;
315 vxi1 *= std::exp(-vxi2 * dt8);
316 vxi2 += g2() * dt4;
317}
318
322 const double dt2 = 0.5 * dt;
323 AtomMatrix vel = matter->getVelocities();
324 AtomMatrix pos = matter->getPositions();
325 double kinE = matter->getKineticEnergy();
326
327 nhcChainHalfStep(vel, kinE);
328
329 pos += vel * dt2;
330 matter->setPositions(pos);
331 AtomMatrix acc = matter->getAccelerations();
332 vel += acc * dt;
333 pos += vel * dt2;
334 matter->setPositions(pos);
335 matter->setVelocities(vel);
336 kinE = matter->getKineticEnergy();
337
338 nhcChainHalfStep(vel, kinE);
339
340 matter->setVelocities(vel);
341}
342
347 const double gamma = m_config.langevin_friction;
348 AtomMatrix pos = matter->getPositions();
349 AtomMatrix vel = matter->getVelocities();
350 AtomMatrix acc = matter->getAccelerations();
351 AtomMatrix noise = AtomMatrix::Zero(nAtoms, 3);
352 const auto mass = matter->getMasses();
353
354 // Zero a frozen axis by assignment. Multiplying by the free mask leaves
355 // a NaN in place, and setPositions stores every component.
356 auto holdFixed = [&](AtomMatrix &m) {
357 for (long i = 0; i < nAtoms; i++) {
358 for (int j = 0; j < 3; j++) {
359 if (matter->getFixed(i, j)) {
360 m(i, j) = 0.0;
361 }
362 }
363 }
364 };
365 auto addNoise = [&]() {
366 noise.setZero();
367 for (long i = 0; i < nAtoms; i++) {
368 for (int j = 0; j < 3; j++) {
369 if (matter->getFixed(i, j)) {
370 continue;
371 }
372 noise(i, j) = std::sqrt(4.0 * gamma * kB * temperature / dt / mass[i]) *
373 eonc::rng::gaussRandom(0.0, 1.0);
374 }
375 }
376 };
377
378 addNoise();
379 AtomMatrix friction = -gamma * vel;
380 holdFixed(friction);
381 holdFixed(acc);
382 acc += friction + noise;
383
384 vel += acc * 0.5 * dt;
385 holdFixed(vel);
386 pos += vel * dt;
387 matter->setPositions(pos);
388
389 acc = matter->getAccelerations();
390 addNoise();
391 friction = -gamma * vel;
392 holdFixed(friction);
393 holdFixed(acc);
394 acc += friction + noise;
395 vel += 0.5 * dt * acc;
396 holdFixed(vel);
397 matter->setVelocities(vel);
398}
399
400} // namespace eonc
Eigen::Matrix< double, 3, 3, eOnStorageOrder > Matrix3d
Definition Eigen.h:35
Eigen::Matrix< double, Eigen::Dynamic, 3, eOnStorageOrder > AtomMatrix
Definition Eigen.h:37
#define EONC_LOG_INFO(...)
Definition EonLogger.h:316
static const char NONE[]
Definition Dynamics.h:78
void setTemperature(double temperature)
Definition Dynamics.cpp:53
static const char LANGEVIN[]
Definition Dynamics.h:77
void setThermalVelocity()
Definition Dynamics.cpp:261
void langevinVerlet()
Langevin dynamics (velocity-Verlet with friction and random forces).
Definition Dynamics.cpp:346
void noseHooverVerlet()
Nose-Hoover chain thermostat (Martyna-Klein-Tuckerman algorithm).
Definition Dynamics.cpp:321
double temperature
Definition Dynamics.h:118
void oneStep(int stepNumber=-1)
Definition Dynamics.cpp:57
void rescaleVelocity()
Definition Dynamics.cpp:278
void andersenCollision()
Definition Dynamics.cpp:238
double pathKineticEnergy_
Definition Dynamics.h:111
static const char ANDERSEN[]
Definition Dynamics.h:75
static const char NOSE_HOOVER[]
Definition Dynamics.h:76
void nhcChainHalfStep(AtomMatrix &vel, double &kinE)
One Martyna-Klein-Tuckerman chain half-step.
Definition Dynamics.cpp:289
Matter * matter
Definition Dynamics.h:113
Dynamics(Matter *matter, const DynamicsConfig &config)
Definition Dynamics.cpp:29
eonc::log::Scoped log
Definition Dynamics.h:120
static const char PILE[]
Definition Dynamics.h:79
static const char PIGLET[]
Definition Dynamics.h:80
void runPathIntegral()
Ring-polymer trajectory. Beads do not enter velocityVerlet.
Definition Dynamics.cpp:104
DynamicsConfig m_config
Definition Dynamics.h:114
void velocityVerlet()
Definition Dynamics.cpp:91
Ring-polymer NVT step.
void setAllBeads(const double *q)
Sample sample(Potential &pot, const double *box, long equilibration, long production)
constexpr bool io_ok(IoStatus s) noexcept
Definition ConFileIO.h:38
double randomDouble()
double gaussRandom(double avg, double std)
constexpr double kHbar
hbar in eV^0.5 amu^0.5 Angstrom, correctly rounded from the exact SI values (h = 6....
Definition Tunneling.h:39
RAII resource manager for the ARTn C library with global synchronization.
Configuration extracted from Parameters for Dynamics.
Definition Dynamics.h:28
double ecoOmegaMax
Highest physical frequency the economised springs reproduce.
std::string gleFile
Normal-mode GLE matrices in normal-mode order.
double pileScale
Scales the critical PILE damping of the internal modes.
double pileTau
Centroid Langevin time, in the same time unit as dt.