Loading...
Searching...
No Matches
PathIntegral.cpp
Go to the documentation of this file.
1/*
2** This file is part of eOn.
3**
4** i-PI Copyright (C) 2014-2015 i-PI developers
5**
6** Permission is hereby granted, free of charge, to any person obtaining
7** a copy of this software and associated documentation files (the
8** "Software"), to deal in the Software without restriction, including
9** without limitation the rights to use, copy, modify, merge, publish,
10** distribute, sublicense, and/or sell copies of the Software, and to
11** permit persons to whom the Software is furnished to do so, subject to
12** the following conditions:
13**
14** The above copyright notice and this permission notice shall be
15** included in all copies or substantial portions of the Software.
16**
17** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20** NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
21** BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
22** ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
23** CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24** SOFTWARE.
25**
26** SPDX-License-Identifier: MIT
27*/
28
29#include "eon/PathIntegral.h"
30
31#include <unsupported/Eigen/MatrixFunctions>
32
33#include <algorithm>
34#include <cctype>
35#include <cmath>
36#include <fstream>
37#include <limits>
38#include <numbers>
39#include <numeric>
40#include <sstream>
41#include <stdexcept>
42#include <utility>
43
45namespace {
46
47constexpr double kPi = std::numbers::pi;
48
49std::string lower(std::string s) {
50 for (char &c : s) {
51 c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
52 }
53 return s;
54}
55
56double ecoResponse(double x) {
57 const double z = 0.5 * x;
58 if (z < 0.25) {
59 const double z2 = z * z;
60 const double denom =
61 1.0 / 3.0 - z2 / 45.0 + 2.0 * z2 * z2 / 945.0 - z2 * z2 * z2 / 4725.0;
62 return 4.0 / denom;
63 }
64 return (x * x) / (z / std::tanh(z) - 1.0);
65}
66
67VectorXd ecoFit(long nBeads, double xmax) {
68 const long nfree = nBeads / 2;
69 VectorXd mult(nfree);
70 mult.setConstant(2.0);
71 if (nBeads % 2 == 0) {
72 mult[nfree - 1] = 1.0;
73 }
74 const long m = std::max(std::lround(10.0 * xmax), 100L);
75 VectorXd x(m);
76 VectorXd f(m);
77 for (long i = 0; i < m; ++i) {
78 x[i] = (static_cast<double>(i) + 0.5) * (xmax / static_cast<double>(m));
79 f[i] = ecoResponse(x[i]);
80 }
81
82 auto objective = [&](const VectorXd &y, double &s, VectorXd &g, MatrixXd &h) {
83 MatrixXd d(m, nfree);
84 MatrixXd e(m, nfree);
85 MatrixXd dg(m, nfree);
86 MatrixXd d2(m, nfree);
87 VectorXd r(m);
88 for (long i = 0; i < m; ++i) {
89 double row = 0.0;
90 for (long k = 0; k < nfree; ++k) {
91 d(i, k) = 1.0 / (y[k] * y[k] + x[i] * x[i]);
92 e(i, k) = f[i] * mult[k] * d(i, k);
93 row += e(i, k);
94 dg(i, k) = -2.0 * d(i, k) * e(i, k) * y[k];
95 d2(i, k) = 2.0 * d(i, k) * d(i, k) * e(i, k) *
96 (3.0 * y[k] * y[k] - x[i] * x[i]);
97 }
98 r[i] = row - 1.0;
99 }
100 s = 0.5 * r.squaredNorm() / static_cast<double>(m);
101 g = VectorXd::Zero(nfree);
102 for (long i = 0; i < m; ++i) {
103 for (long k = 0; k < nfree; ++k) {
104 g[k] += r[i] * dg(i, k);
105 }
106 }
107 g /= static_cast<double>(m);
108 h = dg.transpose() * dg;
109 h += (d2.transpose() * r).asDiagonal();
110 h /= static_cast<double>(m);
111 };
112
113 VectorXd y(nfree);
114 for (long k = 0; k < nfree; ++k) {
115 y[k] = 2.0 * kPi * static_cast<double>(k + 1);
116 }
117 double s = 0.0;
118 VectorXd g(nfree);
119 MatrixXd h(nfree, nfree);
120 objective(y, s, g, h);
121 auto gmaxOf = [](const VectorXd &gg) {
122 double gmax = 0.0;
123 for (long k = 0; k < gg.size(); ++k) {
124 gmax = std::max(gmax, std::fabs(gg[k]));
125 }
126 return gmax;
127 };
128 auto ordered = [&](const VectorXd &z) {
129 if (!(z[0] >= 0.0)) {
130 return false;
131 }
132 for (long k = 1; k < nfree; ++k) {
133 if (!(z[k] >= z[k - 1])) {
134 return false;
135 }
136 }
137 return true;
138 };
139 // Keeps y[0] >= 0 and y ascending. A step that raises the residual is
140 // refused.
141 auto lineSearch = [&](const VectorXd &dy) {
142 double scale = 1.0;
143 for (int cut = 0; cut < 60; ++cut) {
144 const VectorXd z = y + scale * dy;
145 if (ordered(z)) {
146 double sn = 0.0;
147 VectorXd gn(nfree);
148 MatrixXd hn(nfree, nfree);
149 objective(z, sn, gn, hn);
150 if (sn <= s) {
151 y = z;
152 s = sn;
153 g = std::move(gn);
154 h = std::move(hn);
155 return true;
156 }
157 }
158 scale *= 0.5;
159 }
160 return false;
161 };
162
163 // A relative drop with a gradient still above 1e-12 is a stall on the flat
164 // Nyquist mode, not a stationary point. The diagonal step moves that mode.
165 bool exhausted = true;
166 // The near-degenerate high-frequency group leaves a valley whose Hessian
167 // eigenvalues span about twelve decades; the shifted Newton step crosses
168 // it in several hundred iterations, so the cap follows the paper's 10000.
169 for (int iter = 0; iter < 10000; ++iter) {
170 Eigen::SelfAdjointEigenSolver<MatrixXd> es(h);
171 if (es.info() != Eigen::Success) {
172 throw std::runtime_error("economised spring fit: Hessian eigensolve");
173 }
174 const VectorXd eva = es.eigenvalues();
175 const MatrixXd vec = es.eigenvectors();
176 const double delta = std::max(1e-16 * eva[nfree - 1], -2.0 * eva[0]);
177 const VectorXd rhs = vec.transpose() * g;
178 VectorXd scaled(nfree);
179 for (long k = 0; k < nfree; ++k) {
180 scaled[k] = -rhs[k] / (eva[k] + delta);
181 }
182 const VectorXd dy = vec * scaled;
183 const double previous = s;
184 const bool accepted = lineSearch(dy);
185 const double gmax = gmaxOf(g);
186 const bool stationary =
187 accepted && previous - s <= 1e-12 * previous && gmax < 1e-12;
188 if (stationary) {
189 exhausted = false;
190 break;
191 }
192 const bool stalled =
193 !accepted || (previous - s <= 1e-12 * previous && !(gmax < 1e-12));
194 if (stalled) {
195 VectorXd dyDiag(nfree);
196 for (long k = 0; k < nfree; ++k) {
197 const double denom = std::max(std::fabs(h(k, k)), 1e-18);
198 dyDiag[k] = -g[k] / denom;
199 }
200 bool moved = lineSearch(dyDiag);
201 if (!moved) {
202 long worst = 0;
203 double worstAbs = -1.0;
204 for (long k = 0; k < nfree; ++k) {
205 const double a = std::fabs(g[k]);
206 if (a > worstAbs) {
207 worstAbs = a;
208 worst = k;
209 }
210 }
211 VectorXd dyOne = VectorXd::Zero(nfree);
212 const double denom = std::max(std::fabs(h(worst, worst)), 1e-18);
213 dyOne[worst] = -g[worst] / denom;
214 moved = lineSearch(dyOne);
215 }
216 if (!moved) {
217 exhausted = false;
218 break;
219 }
220 if (gmaxOf(g) < 1e-12) {
221 exhausted = false;
222 break;
223 }
224 }
225 }
226 // A cap hit with a tiny objective and gradient is the stationary point.
227 if (exhausted && s > 1e-8 && gmaxOf(g) > 1e-6) {
228 throw std::runtime_error("economised spring fit did not converge");
229 }
230 return y;
231}
232
233MatrixXd factorCovariance(const MatrixXd &cov) {
234 if (cov.rows() == 0 || cov.rows() != cov.cols() || !cov.allFinite()) {
235 throw std::runtime_error("GLE covariance must be finite and square");
236 }
237 const double symmetryTolerance = 64.0 *
238 std::numeric_limits<double>::epsilon() *
239 cov.rows() * cov.cwiseAbs().maxCoeff();
240 if ((cov - cov.transpose()).cwiseAbs().maxCoeff() > symmetryTolerance) {
241 throw std::runtime_error("GLE covariance must be symmetric");
242 }
243 const MatrixXd sym = 0.5 * (cov + cov.transpose());
244 Eigen::SelfAdjointEigenSolver<MatrixXd> es(sym);
245 if (es.info() != Eigen::Success) {
246 throw std::runtime_error("GLE covariance factorisation failed");
247 }
248 const double tolerance = 64.0 * std::numeric_limits<double>::epsilon() *
249 cov.rows() * es.eigenvalues().cwiseAbs().maxCoeff();
250 if (!es.eigenvalues().allFinite() ||
251 es.eigenvalues().minCoeff() < -tolerance) {
252 throw std::runtime_error("GLE covariance is not positive semidefinite");
253 }
254 return es.eigenvectors() *
255 es.eigenvalues().cwiseMax(0.0).cwiseSqrt().asDiagonal();
256}
257
258struct GleFile {
259 long nModes{0};
260 long dim{0};
261 std::vector<MatrixXd> drift;
262 std::vector<MatrixXd> covariance;
263};
264
265GleFile readGle(const std::string &path) {
266 std::ifstream in(path);
267 if (!in) {
268 throw std::runtime_error("cannot read GLE matrices from " + path);
269 }
270 std::vector<double> nums;
271 std::string line;
272 while (std::getline(in, line)) {
273 const auto hash = line.find('#');
274 if (hash != std::string::npos) {
275 line.resize(hash);
276 }
277 std::istringstream ss(line);
278 double v = 0.0;
279 while (ss >> v) {
280 nums.push_back(v);
281 }
282 }
283 if (nums.size() < 2) {
284 throw std::runtime_error("GLE matrix file " + path + " is empty");
285 }
286 GleFile out;
287 out.nModes = std::lround(nums[0]);
288 out.dim = std::lround(nums[1]);
289 if (out.nModes < 1 || out.dim < 1) {
290 throw std::runtime_error("GLE matrix file " + path +
291 " has no modes or no matrix");
292 }
293 const long block = out.dim * out.dim;
294 const long need = 2 + out.nModes * 2 * block;
295 if (static_cast<long>(nums.size()) != need) {
296 throw std::runtime_error("GLE matrix file " + path +
297 " does not match its header");
298 }
299 long cursor = 2;
300 out.drift.resize(static_cast<size_t>(out.nModes));
301 out.covariance.resize(static_cast<size_t>(out.nModes));
302 for (long mode = 0; mode < out.nModes; ++mode) {
303 MatrixXd a(out.dim, out.dim);
304 MatrixXd c(out.dim, out.dim);
305 for (long i = 0; i < out.dim; ++i) {
306 for (long j = 0; j < out.dim; ++j) {
307 a(i, j) = nums[static_cast<size_t>(cursor++)];
308 }
309 }
310 for (long i = 0; i < out.dim; ++i) {
311 for (long j = 0; j < out.dim; ++j) {
312 c(i, j) = nums[static_cast<size_t>(cursor++)];
313 }
314 }
315 out.drift[static_cast<size_t>(mode)] = std::move(a);
316 out.covariance[static_cast<size_t>(mode)] = std::move(c);
317 }
318 return out;
319}
320
321} // namespace
322
323void requireTrotterSprings(const std::string &springs, const char *use) {
324 const std::string s = lower(springs);
325 if (s == "eco" || s == "economised") {
326 throw std::invalid_argument(
327 std::string(use) +
328 " requires Trotter springs; economised springs are refused");
329 }
330}
331
332VectorXd trotterEigenvalues(long nBeads) {
333 if (nBeads < 1) {
334 throw std::invalid_argument("bead count must be positive");
335 }
336 VectorXd eva(nBeads);
337 for (long k = 0; k < nBeads; ++k) {
338 eva[k] = 2.0 * std::sin(kPi * static_cast<double>(k) /
339 static_cast<double>(nBeads));
340 }
341 return eva;
342}
343
344VectorXd ecoEigenvalues(long nBeads, double xmax) {
345 if (nBeads < 1) {
346 throw std::invalid_argument("bead count must be positive");
347 }
348 VectorXd eva = VectorXd::Zero(nBeads);
349 if (nBeads == 1) {
350 return eva;
351 }
352 if (!(xmax > 0.0)) {
353 throw std::invalid_argument(
354 "economised springs need a positive maximum frequency");
355 }
356 const VectorXd y = ecoFit(nBeads, xmax);
357 for (long k = 1; k < nBeads; ++k) {
358 const long pair = std::min(k, nBeads - k) - 1;
359 eva[k] = y[pair] / static_cast<double>(nBeads);
360 }
361 return eva;
362}
363
365 if (nBeads < 1) {
366 throw std::invalid_argument("bead count must be positive");
367 }
368 MatrixXd b = MatrixXd::Zero(nBeads, nBeads);
369 const double n = static_cast<double>(nBeads);
370 for (long j = 0; j < nBeads; ++j) {
371 b(0, j) = 1.0;
372 for (long i = 1; i <= nBeads / 2; ++i) {
373 b(i, j) = std::sqrt(2.0) * std::cos(2.0 * kPi * static_cast<double>(j) *
374 static_cast<double>(i) / n);
375 }
376 for (long i = nBeads / 2 + 1; i < nBeads; ++i) {
377 b(i, j) = std::sqrt(2.0) * std::sin(2.0 * kPi * static_cast<double>(j) *
378 static_cast<double>(i) / n);
379 }
380 }
381 if (nBeads % 2 == 0) {
382 const long mid = nBeads / 2;
383 for (long j = 0; j < nBeads; ++j) {
384 b(mid, j) = (j % 2 == 0) ? 1.0 : -1.0;
385 }
386 }
387 b /= std::sqrt(n);
388 return b;
389}
390
391RingPolymer::RingPolymer(long nAtoms, std::vector<double> masses,
392 std::vector<int> atomicNumbers, std::vector<char> free,
393 Options opt)
394 : opt_(std::move(opt)),
395 nAtoms_(nAtoms),
396 nDof_(3 * nAtoms),
398 atomicNumbers_(std::move(atomicNumbers)),
399 free_(std::move(free)),
400 rng_(opt_.seed == 0 ? 1 : opt_.seed) {
401 if (nAtoms_ < 1 || nBeads_ < 1) {
402 throw std::invalid_argument("path integral needs atoms and beads");
403 }
404 if (static_cast<long>(masses.size()) != nAtoms_ ||
405 static_cast<long>(atomicNumbers_.size()) != nAtoms_ ||
406 static_cast<long>(free_.size()) != nDof_) {
407 throw std::invalid_argument("path integral mass, number or mask size");
408 }
409 if (!(opt_.temperature > 0.0) || !(opt_.kB > 0.0) || !(opt_.hbar > 0.0) ||
410 !(opt_.dt > 0.0) || !(opt_.pileTau > 0.0) || !(opt_.pileScale > 0.0)) {
411 throw std::invalid_argument(
412 "path integral temperature, timestep and damping must be positive");
413 }
414 if (opt_.springs == Springs::Eco && opt_.thermostat == Thermostat::Piglet) {
415 throw std::invalid_argument(
416 "economised springs cannot be combined with a normal-mode GLE");
417 }
418 mass_.assign(static_cast<size_t>(nDof_), 0.0);
419 nFree_ = 0;
420 for (long i = 0; i < nAtoms_; ++i) {
421 if (!(masses[static_cast<size_t>(i)] > 0.0)) {
422 throw std::invalid_argument("path integral atom has no mass");
423 }
424 for (int axis = 0; axis < 3; ++axis) {
425 const long a = 3 * i + axis;
426 mass_[static_cast<size_t>(a)] = masses[static_cast<size_t>(i)];
427 if (free_[static_cast<size_t>(a)]) {
428 freeIndex_.push_back(a);
429 ++nFree_;
430 }
431 }
432 }
433 if (nFree_ < 1) {
434 throw std::invalid_argument("path integral has no free coordinate");
435 }
437 const double omegan =
438 static_cast<double>(nBeads_) * opt_.kB * opt_.temperature / opt_.hbar;
439 if (opt_.springs == Springs::Eco) {
440 const double xmax =
441 opt_.ecoOmegaMax * opt_.hbar / (opt_.kB * opt_.temperature);
442 omegaK_ = omegan * ecoEigenvalues(nBeads_, xmax);
443 } else {
445 }
446 halfDt_ = 0.5 * opt_.dt;
447 cosHalf_.resize(static_cast<size_t>(nBeads_));
448 sinHalf_.resize(static_cast<size_t>(nBeads_));
449 cosFull_.resize(static_cast<size_t>(nBeads_));
450 sinFull_.resize(static_cast<size_t>(nBeads_));
451 for (long k = 0; k < nBeads_; ++k) {
452 const double w = omegaK_[k];
453 cosHalf_[static_cast<size_t>(k)] = std::cos(w * halfDt_);
454 sinHalf_[static_cast<size_t>(k)] = std::sin(w * halfDt_);
455 cosFull_[static_cast<size_t>(k)] = std::cos(w * opt_.dt);
456 sinFull_[static_cast<size_t>(k)] = std::sin(w * opt_.dt);
457 }
458 q_.assign(static_cast<size_t>(nBeads_), VectorXd::Zero(nDof_));
459 p_.assign(static_cast<size_t>(nBeads_), VectorXd::Zero(nDof_));
460 f_.assign(static_cast<size_t>(nBeads_), VectorXd::Zero(nDof_));
461 qnm_.assign(static_cast<size_t>(nBeads_), VectorXd::Zero(nDof_));
462 pnm_.assign(static_cast<size_t>(nBeads_), VectorXd::Zero(nDof_));
463 if (opt_.thermostat == Thermostat::Piglet) {
464 initGle();
465 }
467}
468
470 if (nBeads_ == 1 && opt_.gleFile.empty()) {
471 gle_.resize(1);
472 return;
473 }
474 if (opt_.gleFile.empty()) {
475 throw std::invalid_argument("normal-mode GLE needs a matrix file");
476 }
477 const GleFile file = readGle(opt_.gleFile);
478 const long first = file.nModes == nBeads_ ? 0 : 1;
479 if (file.nModes != nBeads_ && file.nModes != nBeads_ - 1) {
480 throw std::invalid_argument(
481 "GLE matrix count must be the bead count or one less");
482 }
483 const double h = 0.5 * opt_.dt;
484 gle_.resize(static_cast<size_t>(nBeads_));
485 for (long k = first; k < nBeads_; ++k) {
486 const long src = k - first;
487 ModeGle mode;
488 mode.drift = file.drift[static_cast<size_t>(src)];
489 mode.covariance = file.covariance[static_cast<size_t>(src)];
490 mode.propagate = (-mode.drift * h).exp();
491 const MatrixXd cov =
492 opt_.kB * (mode.covariance - mode.propagate * mode.covariance *
493 mode.propagate.transpose());
494 mode.noise = factorCovariance(cov);
495 mode.extended = MatrixXd::Zero(file.dim, nFree_);
496 mode.draw = MatrixXd::Zero(file.dim, nFree_);
497 mode.acc = MatrixXd::Zero(file.dim, nFree_);
498 gle_[static_cast<size_t>(k)] = std::move(mode);
499 }
500}
501
502void RingPolymer::setAllBeads(const double *q) {
503 if (q == nullptr) {
504 throw std::invalid_argument("path integral positions are missing");
505 }
506 for (long bead = 0; bead < nBeads_; ++bead) {
507 for (long a = 0; a < nDof_; ++a) {
508 q_[static_cast<size_t>(bead)][a] = q[a];
509 }
510 }
511 if (constrain_) {
513 }
514 haveForces_ = false;
515}
516
517void RingPolymer::setBeads(const std::vector<VectorXd> &beads) {
518 if (static_cast<long>(beads.size()) != nBeads_) {
519 throw std::invalid_argument("path integral bead count mismatch");
520 }
521 for (long bead = 0; bead < nBeads_; ++bead) {
522 if (beads[static_cast<size_t>(bead)].size() != nDof_) {
523 throw std::invalid_argument("path integral bead has the wrong length");
524 }
525 q_[static_cast<size_t>(bead)] = beads[static_cast<size_t>(bead)];
526 }
527 if (constrain_) {
529 }
530 haveForces_ = false;
531}
532
533void RingPolymer::setMomenta(const std::vector<VectorXd> &momenta) {
534 if (static_cast<long>(momenta.size()) != nBeads_) {
535 throw std::invalid_argument("path integral bead count mismatch");
536 }
537 for (long bead = 0; bead < nBeads_; ++bead) {
538 if (momenta[static_cast<size_t>(bead)].size() != nDof_) {
539 throw std::invalid_argument(
540 "path integral momentum has the wrong length");
541 }
542 for (long a = 0; a < nDof_; ++a) {
543 p_[static_cast<size_t>(bead)][a] =
544 free_[static_cast<size_t>(a)] ? momenta[static_cast<size_t>(bead)][a]
545 : 0.0;
546 }
547 }
548}
549
550void RingPolymer::setHyperplane(const VectorXd &normal,
551 const VectorXd &origin) {
552 if (normal.size() != nDof_ || origin.size() != nDof_) {
553 throw std::invalid_argument("hyperplane vectors have the wrong length");
554 }
555 planeNormal_ = VectorXd::Zero(nDof_);
556 planeOrigin_ = origin;
557 double norm = 0.0;
558 for (long a : freeIndex_) {
559 planeNormal_[a] = normal[a];
560 norm += normal[a] * normal[a];
561 }
562 if (!(norm > 0.0)) {
563 throw std::invalid_argument("hyperplane normal has no free component");
564 }
565 planeNormal_ /= std::sqrt(norm);
566 constrain_ = true;
569 haveForces_ = false;
570}
571
573 rng_ = rng_ * 6364136223846793005ULL + 1ULL;
574 const double u1 =
575 std::max((rng_ >> 11) * (1.0 / 9007199254740992.0), 1.0e-16);
576 rng_ = rng_ * 6364136223846793005ULL + 1ULL;
577 const double u2 = (rng_ >> 11) * (1.0 / 9007199254740992.0);
578 return std::sqrt(-2.0 * std::log(u1)) * std::cos(2.0 * kPi * u2);
579}
580
582 for (long bead = 0; bead < nBeads_; ++bead) {
583 p_[static_cast<size_t>(bead)].setZero();
584 }
585 toNormal(p_, pnm_);
586 const double tSim = static_cast<double>(nBeads_) * opt_.kB * opt_.temperature;
587 for (long k = 0; k < nBeads_; ++k) {
588 const bool gleMode = opt_.thermostat == Thermostat::Piglet &&
589 gle_[static_cast<size_t>(k)].extended.rows() > 0;
590 if (gleMode) {
591 continue;
592 }
593 for (long a : freeIndex_) {
594 pnm_[static_cast<size_t>(k)][a] =
595 gauss() * std::sqrt(mass_[static_cast<size_t>(a)] * tSim);
596 }
597 }
598 if (opt_.thermostat == Thermostat::Piglet) {
599 for (long k = 0; k < nBeads_; ++k) {
600 ModeGle &mode = gle_[static_cast<size_t>(k)];
601 if (mode.extended.rows() == 0) {
602 continue;
603 }
604 const MatrixXd factor = factorCovariance(opt_.kB * mode.covariance);
605 MatrixXd noise(mode.extended.rows(), mode.extended.cols());
606 for (long r = 0; r < noise.rows(); ++r) {
607 for (long c = 0; c < noise.cols(); ++c) {
608 noise(r, c) = gauss();
609 }
610 }
611 mode.extended = factor * noise;
612 for (long col = 0; col < nFree_; ++col) {
613 const long a = freeIndex_[static_cast<size_t>(col)];
614 pnm_[static_cast<size_t>(k)][a] =
615 mode.extended(0, col) * std::sqrt(mass_[static_cast<size_t>(a)]);
616 }
617 }
618 }
621 haveForces_ = false;
622}
623
624void RingPolymer::toNormal(const std::vector<VectorXd> &src,
625 std::vector<VectorXd> &dst) const {
626 // modes_ is row-major: modes(k, j) lives at k * nBeads + j.
627 // Fixed coordinates are not ring degrees of freedom, so they stay in
628 // bead space and are left out of the multiply.
629 const double *mode = modes_.data();
630 const long n = nBeads_;
631 for (long a : freeIndex_) {
632 for (long k = 0; k < n; ++k) {
633 double sum = 0.0;
634 const double *row = mode + k * n;
635 for (long j = 0; j < n; ++j) {
636 sum += src[static_cast<size_t>(j)][a] * row[j];
637 }
638 dst[static_cast<size_t>(k)][a] = sum;
639 }
640 }
641}
642
643void RingPolymer::fromNormal(const std::vector<VectorXd> &src,
644 std::vector<VectorXd> &dst) const {
645 const double *mode = modes_.data();
646 const long n = nBeads_;
647 for (long a : freeIndex_) {
648 for (long j = 0; j < n; ++j) {
649 double sum = 0.0;
650 for (long k = 0; k < n; ++k) {
651 sum += src[static_cast<size_t>(k)][a] * mode[k * n + j];
652 }
653 dst[static_cast<size_t>(j)][a] = sum;
654 }
655 }
656}
657
658void RingPolymer::forces(Potential &pot, const double *box) {
659 double zeroBox[9] = {};
660 const double *cell = box != nullptr ? box : zeroBox;
661 const auto n = static_cast<size_t>(nBeads_);
662 posPtr_.resize(n);
663 nrsPtr_.resize(n);
664 frcPtr_.resize(n);
665 boxPtr_.assign(n, cell);
666 energyBuf_.assign(n, 0.0);
667 varianceBuf_.assign(n, 0.0);
668 for (long bead = 0; bead < nBeads_; ++bead) {
669 posPtr_[static_cast<size_t>(bead)] = q_[static_cast<size_t>(bead)].data();
670 nrsPtr_[static_cast<size_t>(bead)] = atomicNumbers_.data();
671 frcPtr_[static_cast<size_t>(bead)] = f_[static_cast<size_t>(bead)].data();
672 }
673 // The bead index is each system's identity across steps: a potential
674 // that spreads the ring over calculators keeps a bead on one calculator,
675 // and one that stores per-system state (cpmdc orbitals) keeps it with
676 // the bead.
677 if (owners_.size() != n) {
678 owners_.resize(n);
679 std::iota(owners_.begin(), owners_.end(), 0L);
680 }
681 pot.forceBatchOwned(nBeads_, nAtoms_, posPtr_.data(), nrsPtr_.data(),
682 frcPtr_.data(), energyBuf_.data(), varianceBuf_.data(),
683 boxPtr_.data(), owners_.data());
684 ++batches_;
685 for (long bead = 0; bead < nBeads_; ++bead) {
686 for (long a = 0; a < nDof_; ++a) {
687 if (!free_[static_cast<size_t>(a)]) {
688 f_[static_cast<size_t>(bead)][a] = 0.0;
689 }
690 }
691 }
692 haveForces_ = true;
693}
694
695VectorXd RingPolymer::centroid() const {
696 VectorXd c = VectorXd::Zero(nDof_);
697 for (long bead = 0; bead < nBeads_; ++bead) {
698 c += q_[static_cast<size_t>(bead)];
699 }
700 c /= static_cast<double>(nBeads_);
701 return c;
702}
703
705 std::vector<VectorXd> pnm(static_cast<size_t>(nBeads_),
706 VectorXd::Zero(nDof_));
707 toNormal(p_, pnm);
708 VectorXd v = VectorXd::Zero(nDof_);
709 const double scale = std::sqrt(static_cast<double>(nBeads_));
710 for (long a = 0; a < nDof_; ++a) {
711 const double m = mass_[static_cast<size_t>(a)];
712 if (m > 0.0) {
713 v[a] = pnm[0][a] / (scale * m);
714 }
715 }
716 return v;
717}
718
720 double k = 0.5 * static_cast<double>(nFree_) * opt_.kB * opt_.temperature;
721 if (!haveForces_) {
722 return k;
723 }
724 if (centroid_.size() != nDof_) {
725 centroid_.resize(nDof_);
726 }
727 centroid_.setZero();
728 for (long bead = 0; bead < nBeads_; ++bead) {
729 centroid_ += q_[static_cast<size_t>(bead)];
730 }
731 centroid_ /= static_cast<double>(nBeads_);
732 double virial = 0.0;
733 for (long bead = 0; bead < nBeads_; ++bead) {
734 for (long a : freeIndex_) {
735 virial += (q_[static_cast<size_t>(bead)][a] - centroid_[a]) *
736 f_[static_cast<size_t>(bead)][a];
737 }
738 }
739 k += -0.5 / static_cast<double>(nBeads_) * virial;
740 return k;
741}
742
744 if (!constrain_ || recorded_ < 1) {
745 return 0.0;
746 }
747 return forceSum_ / static_cast<double>(recorded_);
748}
749
751 recorded_ = 0;
752 kineticSum_ = 0.0;
753 forceSum_ = 0.0;
754}
755
757 toNormal(p_, pnm_);
758 const double tSim = static_cast<double>(nBeads_) * opt_.kB * opt_.temperature;
759 auto langevin = [&](long k, double tau) {
760 const double damp = std::exp(-h / tau);
761 const double noise = std::sqrt(tSim * (1.0 - damp * damp));
762 for (long a : freeIndex_) {
763 const double sm = std::sqrt(mass_[static_cast<size_t>(a)]);
764 double pms = pnm_[static_cast<size_t>(k)][a] / sm;
765 pms = damp * pms + noise * gauss();
766 pnm_[static_cast<size_t>(k)][a] = pms * sm;
767 }
768 };
769 for (long k = 0; k < nBeads_; ++k) {
770 if (opt_.thermostat == Thermostat::Piglet &&
771 gle_[static_cast<size_t>(k)].extended.rows() > 0) {
772 ModeGle &mode = gle_[static_cast<size_t>(k)];
773 for (long col = 0; col < nFree_; ++col) {
774 const long a = freeIndex_[static_cast<size_t>(col)];
775 mode.extended(0, col) = pnm_[static_cast<size_t>(k)][a] /
776 std::sqrt(mass_[static_cast<size_t>(a)]);
777 }
778 MatrixXd &draw = mode.draw;
779 for (long r = 0; r < draw.rows(); ++r) {
780 for (long c = 0; c < draw.cols(); ++c) {
781 draw(r, c) = gauss();
782 }
783 }
784 mode.acc.noalias() = mode.propagate * mode.extended;
785 mode.acc.noalias() += mode.noise * draw;
786 mode.extended.swap(mode.acc);
787 for (long col = 0; col < nFree_; ++col) {
788 const long a = freeIndex_[static_cast<size_t>(col)];
789 pnm_[static_cast<size_t>(k)][a] =
790 mode.extended(0, col) * std::sqrt(mass_[static_cast<size_t>(a)]);
791 }
792 } else {
793 const double tau =
794 k == 0 ? opt_.pileTau : 1.0 / (2.0 * opt_.pileScale * omegaK_[k]);
795 langevin(k, tau);
796 }
797 }
799}
800
801void RingPolymer::kick(double h, bool dropParallel) {
802 if (!(dropParallel && constrain_)) {
803 for (long bead = 0; bead < nBeads_; ++bead) {
804 for (long a : freeIndex_) {
805 p_[static_cast<size_t>(bead)][a] +=
806 f_[static_cast<size_t>(bead)][a] * h;
807 }
808 }
809 return;
810 }
811 VectorXd removal = VectorXd::Zero(nDof_);
812 if (dropParallel && constrain_) {
813 VectorXd fc = VectorXd::Zero(nDof_);
814 for (long bead = 0; bead < nBeads_; ++bead) {
815 fc += f_[static_cast<size_t>(bead)];
816 }
817 fc /= static_cast<double>(nBeads_);
818 double along = 0.0;
819 for (long a : freeIndex_) {
820 along += planeNormal_[a] * fc[a];
821 }
822 removal = along * planeNormal_;
823 }
824 for (long bead = 0; bead < nBeads_; ++bead) {
825 for (long a : freeIndex_) {
826 p_[static_cast<size_t>(bead)][a] +=
827 (f_[static_cast<size_t>(bead)][a] - removal[a]) * h;
828 }
829 }
830}
831
833 toNormal(q_, qnm_);
834 toNormal(p_, pnm_);
835 const double *cosH = nullptr;
836 const double *sinH = nullptr;
837 if (h == halfDt_) {
838 cosH = cosHalf_.data();
839 sinH = sinHalf_.data();
840 } else if (h == opt_.dt) {
841 cosH = cosFull_.data();
842 sinH = sinFull_.data();
843 }
844 for (long a : freeIndex_) {
845 const double m = mass_[static_cast<size_t>(a)];
846 qnm_[0][a] += pnm_[0][a] / m * h;
847 for (long k = 1; k < nBeads_; ++k) {
848 const double omega = omegaK_[k];
849 const double c = cosH != nullptr ? cosH[k] : std::cos(omega * h);
850 const double s = sinH != nullptr ? sinH[k] : std::sin(omega * h);
851 const double pk = pnm_[static_cast<size_t>(k)][a];
852 const double qk = qnm_[static_cast<size_t>(k)][a];
853 pnm_[static_cast<size_t>(k)][a] = c * pk - m * omega * s * qk;
854 qnm_[static_cast<size_t>(k)][a] = c * qk + s * pk / (omega * m);
855 }
856 }
859}
860
861// The centroid mode is the bead sum over sqrt(P), so a change d of that
862// mode moves every bead by d / sqrt(P) and leaves the other modes alone.
864 if (!constrain_) {
865 return;
866 }
867 const VectorXd c = centroid();
868 double sigma = 0.0;
869 for (long a : freeIndex_) {
870 sigma += planeNormal_[a] * (c[a] - planeOrigin_[a]);
871 }
872 for (long bead = 0; bead < nBeads_; ++bead) {
873 for (long a : freeIndex_) {
874 q_[static_cast<size_t>(bead)][a] -= sigma * planeNormal_[a];
875 }
876 }
877}
878
880 if (!constrain_) {
881 return;
882 }
883 VectorXd sum = VectorXd::Zero(nDof_);
884 for (long bead = 0; bead < nBeads_; ++bead) {
885 sum += p_[static_cast<size_t>(bead)];
886 }
887 // p_0 = sum / sqrt(P); remove lambda n from p_0.
888 const double scale = std::sqrt(static_cast<double>(nBeads_));
889 double num = 0.0;
890 double den = 0.0;
891 for (long a : freeIndex_) {
892 const double m = mass_[static_cast<size_t>(a)];
893 num += planeNormal_[a] * (sum[a] / scale) / m;
894 den += planeNormal_[a] * planeNormal_[a] / m;
895 }
896 if (den > 0.0) {
897 const double shift = num / den / scale;
898 for (long bead = 0; bead < nBeads_; ++bead) {
899 for (long a : freeIndex_) {
900 p_[static_cast<size_t>(bead)][a] -= shift * planeNormal_[a];
901 }
902 }
903 if (opt_.thermostat == Thermostat::Piglet && !gle_.empty()) {
904 auto &state = gle_[0].extended;
905 // The spatial constraint projector acts on every auxiliary row.
906 // It commutes with the OU matrix, which acts on auxiliary indices.
907 for (long row = 0; row < state.rows(); ++row) {
908 double along = 0.0;
909 for (long col = 0; col < nFree_; ++col) {
910 const long a = freeIndex_[static_cast<size_t>(col)];
911 along += state(row, col) * planeNormal_[a] /
912 std::sqrt(mass_[static_cast<size_t>(a)]);
913 }
914 for (long col = 0; col < nFree_; ++col) {
915 const long a = freeIndex_[static_cast<size_t>(col)];
916 state(row, col) -= along / den * planeNormal_[a] /
917 std::sqrt(mass_[static_cast<size_t>(a)]);
918 }
919 }
920 }
921 }
922}
923
924void RingPolymer::step(Potential &pot, const double *box, bool record) {
925 const double half = 0.5 * opt_.dt;
926 thermostat(half);
928 // The thermostat and the momentum projection leave the beads where the
929 // last step evaluated them.
930 if (!haveForces_) {
931 forces(pot, box);
932 }
933 kick(half, true);
935 // Two free half-steps are one full step of the exact ring propagator.
936 propagate(opt_.dt);
938 forces(pot, box);
939 if (record) {
941 if (constrain_) {
942 VectorXd fc = VectorXd::Zero(nDof_);
943 for (long bead = 0; bead < nBeads_; ++bead) {
944 fc += f_[static_cast<size_t>(bead)];
945 }
946 fc /= static_cast<double>(nBeads_);
947 double along = 0.0;
948 for (long a : freeIndex_) {
949 along += planeNormal_[a] * fc[a];
950 }
951 forceSum_ += along;
952 }
953 ++recorded_;
954 }
955 kick(half, true);
957 thermostat(half);
959}
960
961void RingPolymer::nveStep(Potential &pot, const double *box) {
962 if (constrain_) {
963 throw std::logic_error("path integral NVE step with a hyperplane set");
964 }
965 const double half = 0.5 * opt_.dt;
966 if (!haveForces_) {
967 forces(pot, box);
968 }
969 kick(half, false);
970 propagate(opt_.dt);
971 forces(pot, box);
972 kick(half, false);
973}
974
976 long equilibration, long production) {
977 if (equilibration < 0 || production < 1) {
978 throw std::invalid_argument("path integral sample length");
979 }
980 for (long step = 0; step < equilibration; ++step) {
981 this->step(pot, box, false);
982 }
984 const long batchesBefore = batches_;
985 for (long step = 0; step < production; ++step) {
986 this->step(pot, box, true);
987 }
988 Sample out;
989 out.kineticCv = kineticSum_ / static_cast<double>(recorded_);
990 out.meanForce = meanForce();
991 out.batches = batches_ - batchesBefore;
992 return out;
993}
994
995} // namespace eonc::pathintegral
Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic, eOnStorageOrder > MatrixXd
Definition Eigen.h:33
std::vector< int > atomicNumbers_
void setAllBeads(const double *q)
std::vector< long > freeIndex_
std::vector< VectorXd > pnm_
std::vector< double > varianceBuf_
std::vector< ModeGle > gle_
std::vector< double > mass_
std::vector< const int * > nrsPtr_
std::vector< double * > frcPtr_
std::vector< VectorXd > f_
void setMomenta(const std::vector< VectorXd > &momenta)
One momentum vector of length 3 * nAtoms per bead; fixed coordinates are zeroed.
void nveStep(Potential &pot, const double *box)
Thermostat-free RPMD step: velocity Verlet with the free ring propagated exactly in normal modes.
std::vector< const double * > posPtr_
RingPolymer(long nAtoms, std::vector< double > masses, std::vector< int > atomicNumbers, std::vector< char > free, Options opt)
Sample sample(Potential &pot, const double *box, long equilibration, long production)
void toNormal(const std::vector< VectorXd > &src, std::vector< VectorXd > &dst) const
void setBeads(const std::vector< VectorXd > &beads)
One position vector of length 3 * nAtoms per bead.
std::vector< double > cosFull_
std::vector< VectorXd > p_
void forces(Potential &pot, const double *box)
void setHyperplane(const VectorXd &normal, const VectorXd &origin)
Hold n · (q_centroid - origin) = 0.
std::vector< VectorXd > q_
void kick(double h, bool dropParallel)
void step(Potential &pot, const double *box, bool record)
const std::vector< VectorXd > & momenta() const
std::vector< double > sinFull_
void fromNormal(const std::vector< VectorXd > &src, std::vector< VectorXd > &dst) const
std::vector< double > energyBuf_
const std::vector< VectorXd > & beads() const
std::vector< double > sinHalf_
std::vector< VectorXd > qnm_
std::vector< const double * > boxPtr_
std::vector< double > cosHalf_
MatrixXd normalModeMatrix(long nBeads)
Orthogonal bead-to-normal-mode matrix. Row k is mode k.
VectorXd trotterEigenvalues(long nBeads)
Dimensionless free-ring eigenvalues, mode 0 equal to 0.
void requireTrotterSprings(const std::string &springs, const char *use)
Economised springs and a normal-mode GLE are refused.
VectorXd ecoEigenvalues(long nBeads, double xmax)
double meanForce
Average of n · f_centroid.