Loading...
Searching...
No Matches
PIQTST.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/PIQTST.h"
13
14#include <algorithm>
15#include <cmath>
16#include <limits>
17#include <numbers>
18#include <stdexcept>
19#include <string>
20
21namespace eonc::piqtst {
22
23namespace {
24
26MatrixXd trapezoidWeights(const std::vector<Plane> &planes) {
27 const long n = static_cast<long>(planes.size());
28 MatrixXd w = MatrixXd::Zero(n, n);
29 for (long j = 1; j < n; ++j) {
30 w.row(j) = w.row(j - 1);
31 const double h =
32 planes[static_cast<size_t>(j)].s - planes[static_cast<size_t>(j - 1)].s;
33 w(j, j - 1) += 0.5 * h;
34 w(j, j) += 0.5 * h;
35 }
36 return w;
37}
38
39VectorXd forceErrors(const std::vector<Plane> &planes) {
40 VectorXd e(static_cast<long>(planes.size()));
41 for (size_t i = 0; i < planes.size(); ++i) {
42 e(static_cast<long>(i)) = planes[i].meanForceError;
43 }
44 return e;
45}
46
47double propagated(const VectorXd &gradient, const VectorXd &errors) {
48 return std::sqrt(gradient.cwiseProduct(errors).squaredNorm());
49}
50
54struct Axes {
55 VectorXd a;
56 VectorXd b;
57};
58
59Axes axes(const Coordinate &c) {
60 const long dof = 3 * c.atoms;
61 if (c.atoms < 1 || static_cast<long>(c.masses.size()) != c.atoms ||
62 static_cast<long>(c.free.size()) != dof || c.reference.size() != dof ||
63 c.direction.size() != dof) {
64 throw std::invalid_argument("piqtst: coordinate sizes do not match");
65 }
66 Axes out{VectorXd::Zero(dof), VectorXd::Zero(dof)};
67 double nn = 0.0;
68 for (long i = 0; i < dof; ++i) {
69 if (!c.free[static_cast<size_t>(i)]) {
70 continue;
71 }
72 const double sm = std::sqrt(c.masses[static_cast<size_t>(i / 3)]);
73 out.a(i) = sm * c.direction(i);
74 out.b(i) = c.direction(i) / sm;
75 nn += c.direction(i) * c.direction(i);
76 }
77 if (std::abs(nn - 1.0) > 1e-8) {
78 throw std::invalid_argument(
79 "piqtst: the direction must be a unit vector on the free coordinates");
80 }
81 return out;
82}
83
84} // namespace
85
86void integrate(std::vector<Plane> &planes) {
87 if (planes.empty()) {
88 return;
89 }
90 const MatrixXd w = trapezoidWeights(planes);
91 VectorXd f(static_cast<long>(planes.size()));
92 for (size_t i = 0; i < planes.size(); ++i) {
93 f(static_cast<long>(i)) = planes[i].meanForce;
94 }
95 const VectorXd errors = forceErrors(planes);
96 const VectorXd values = w * f;
97 for (size_t j = 0; j < planes.size(); ++j) {
98 planes[j].freeEnergy = values(static_cast<long>(j));
99 planes[j].freeEnergyError =
100 propagated(w.row(static_cast<long>(j)).transpose(), errors);
101 }
102}
103
104std::vector<Plane> scan(Potential &pot, const Coordinate &c,
105 const ScanOptions &o) {
106 const long dof = 3 * c.atoms;
107 const Axes ax = axes(c);
108 const VectorXd &a = ax.a;
109 const VectorXd &b = ax.b;
110 if (o.planes.size() < 2) {
111 throw std::invalid_argument("piqtst: at least two planes are needed");
112 }
113 for (size_t j = 1; j < o.planes.size(); ++j) {
114 if (!(o.planes[j] > o.planes[j - 1])) {
115 throw std::invalid_argument("piqtst: plane positions must ascend");
116 }
117 }
118 if (o.equilibration < 0 || o.production < 2 || o.blocks < 2 ||
119 o.production < o.blocks) {
120 throw std::invalid_argument(
121 "piqtst: sampling needs at least as many steps as blocks, and two "
122 "blocks");
123 }
124 const double aNorm = a.norm();
125 auto seedAt = [&](double s) -> VectorXd {
126 if (o.seed) {
127 VectorXd x = o.seed(s);
128 if (x.size() != dof) {
129 throw std::invalid_argument("piqtst: a seed has the wrong length");
130 }
131 return x;
132 }
133 return c.reference + s * b;
134 };
135
137 const long beads = o.ring.beads;
138 const long blockSize = o.production / o.blocks;
139 std::vector<Plane> out;
140 out.reserve(o.planes.size());
141 for (size_t j = 0; j < o.planes.size(); ++j) {
142 const double s = o.planes[j];
143 const VectorXd origin = c.reference + s * b;
144 const VectorXd target = seedAt(s);
145 if (j == 0) {
146 ring.setAllBeads(target.data());
147 } else {
148 const VectorXd shift = target - ring.centroid();
149 std::vector<VectorXd> moved = ring.beads();
150 for (auto &q : moved) {
151 q += shift;
152 }
153 ring.setBeads(moved);
154 }
155 ring.setHyperplane(a, origin);
156
157 const long batches0 = ring.batches();
158 for (long step = 0; step < o.equilibration; ++step) {
159 ring.step(pot, c.box, false);
160 }
161 Plane plane;
162 plane.s = s;
163 plane.centroid = VectorXd::Zero(dof);
164 VectorXd spread2 = VectorXd::Zero(dof);
165 double sum = 0.0;
166 double blockSum = 0.0;
167 std::vector<double> blockMeans;
168 for (long step = 0; step < o.production; ++step) {
169 ring.resetAverages();
170 ring.step(pot, c.box, true);
171 const double fn = ring.meanForce();
172 sum += fn;
173 blockSum += fn;
174 if ((step + 1) % blockSize == 0 &&
175 static_cast<long>(blockMeans.size()) < o.blocks) {
176 blockMeans.push_back(blockSum / static_cast<double>(blockSize));
177 blockSum = 0.0;
178 }
179 const VectorXd centroid = ring.centroid();
180 plane.centroid += centroid;
181 for (const auto &q : ring.beads()) {
182 spread2 += (q - centroid).cwiseAbs2();
183 }
184 }
185 const double steps = static_cast<double>(o.production);
186 plane.centroid /= steps;
187 spread2 /= steps * static_cast<double>(beads);
188 plane.spread.resize(static_cast<size_t>(dof));
189 for (long i = 0; i < dof; ++i) {
190 plane.spread[static_cast<size_t>(i)] = std::sqrt(spread2(i));
191 }
192 const double mean = sum / steps;
193 double blockMean = 0.0;
194 for (const double m : blockMeans) {
195 blockMean += m;
196 }
197 const double nb = static_cast<double>(blockMeans.size());
198 blockMean /= nb;
199 double var = 0.0;
200 for (const double m : blockMeans) {
201 var += (m - blockMean) * (m - blockMean);
202 }
203 var /= nb * (nb - 1.0);
204 plane.meanForce = -mean / aNorm;
205 plane.meanForceError = std::sqrt(var) / aNorm;
206 plane.batches = ring.batches() - batches0;
207 out.push_back(std::move(plane));
208 }
209 integrate(out);
210 return out;
211}
212
213Rate rate(const std::vector<Plane> &planes, double beta) {
214 const long n = static_cast<long>(planes.size());
215 if (n < 2) {
216 throw std::invalid_argument("piqtst: the rate needs two planes");
217 }
218 if (!(beta > 0.0)) {
219 throw std::invalid_argument("piqtst: the rate needs a positive beta");
220 }
221 const MatrixXd w = trapezoidWeights(planes);
222 const VectorXd errors = forceErrors(planes);
223 Rate r;
224 // The reactant is the lowest F before the dividing plane; s* itself is
225 // the top, and a minimum there is a plane that is no barrier, which the
226 // barrier's sign then shows.
227 const long top = n - 1;
228 double fMin = std::numeric_limits<double>::infinity();
229 for (long j = 0; j < top; ++j) {
230 const double f = planes[static_cast<size_t>(j)].freeEnergy;
231 if (f < fMin) {
232 fMin = f;
233 r.reactant = j;
234 }
235 }
236 const double fTop = planes[static_cast<size_t>(top)].freeEnergy;
237 r.barrier = fTop - fMin;
238 r.barrierError =
239 propagated((w.row(top) - w.row(r.reactant)).transpose(), errors);
240 r.firstPlaneHeight = beta * (planes.front().freeEnergy - fMin);
241
242 // Z = int exp(-beta F) ds by the trapezoid rule, referenced to fMin.
243 VectorXd weight(n);
244 double z = 0.0;
245 for (long j = 0; j < n; ++j) {
246 const double left = j > 0 ? planes[static_cast<size_t>(j)].s -
247 planes[static_cast<size_t>(j - 1)].s
248 : 0.0;
249 const double right = j + 1 < n ? planes[static_cast<size_t>(j + 1)].s -
250 planes[static_cast<size_t>(j)].s
251 : 0.0;
252 weight(j) =
253 0.5 * (left + right) *
254 std::exp(-beta * (planes[static_cast<size_t>(j)].freeEnergy - fMin));
255 z += weight(j);
256 }
257 weight /= z;
258 r.logRate = std::log(0.5 * std::sqrt(2.0 / (std::numbers::pi * beta))) -
259 beta * (fTop - fMin) - std::log(z);
260 const VectorXd gradient =
261 -beta * w.row(top).transpose() + beta * (w.transpose() * weight);
262 r.logRateError = propagated(gradient, errors);
263 return r;
264}
265
267 const RecrossingOptions &o) {
268 const long dof = 3 * c.atoms;
269 const Axes ax = axes(c);
270 if (o.parents < 2 || o.children < 1 || o.spacing < 1 || o.steps < 4 ||
271 o.equilibration < 0) {
272 throw std::invalid_argument(
273 "piqtst: recrossing needs two parents, one child, a positive "
274 "spacing and four steps");
275 }
276 const VectorXd origin = c.reference + o.s * ax.b;
277 VectorXd start = origin;
278 if (o.seed) {
279 start = o.seed(o.s);
280 if (start.size() != dof) {
281 throw std::invalid_argument("piqtst: a seed has the wrong length");
282 }
283 }
284 // Bennett-Chandler needs parents from the ring polymer's own constrained
285 // Boltzmann distribution. PIGLET's coloured noise samples another one,
286 // tuned for bead averages, so the parents always take PILE.
287 pathintegral::Options parentOptions = o.ring;
289 parentOptions.gleFile.clear();
291 parentOptions);
292 parent.setAllBeads(start.data());
293 parent.setHyperplane(ax.a, origin);
294 for (long step = 0; step < o.equilibration; ++step) {
295 parent.step(pot, c.box, false);
296 }
297
298 // The children draw every normal mode from the free-ring Boltzmann
299 // distribution at beta / P, which PILE's initial momenta are, and carry
300 // their own stream so parent and child noise stay independent.
301 pathintegral::Options childOptions = o.ring;
303 childOptions.gleFile.clear();
304 childOptions.seed = o.ring.seed + 0x9E3779B97F4A7C15ULL;
306 childOptions);
307
308 const long n = o.steps + 1;
309 // Per parent: sum over children of sdot(0) h(s(t) - s*) at each time,
310 // and of sdot(0) h(sdot(0)).
311 std::vector<VectorXd> numerator(static_cast<size_t>(o.parents),
312 VectorXd::Zero(n));
313 std::vector<double> denominator(static_cast<size_t>(o.parents), 0.0);
314 Recrossing out;
315 for (long p = 0; p < o.parents; ++p) {
316 for (long step = 0; step < o.spacing; ++step) {
317 parent.step(pot, c.box, false);
318 }
319 const std::vector<VectorXd> beads = parent.beads();
320 VectorXd &num = numerator[static_cast<size_t>(p)];
321 double &den = denominator[static_cast<size_t>(p)];
322 for (long k = 0; k < o.children; ++k) {
323 child.setBeads(beads);
324 child.thermalMomenta();
325 std::vector<VectorXd> reversed = child.momenta();
326 const double forward = ax.a.dot(child.centroidVelocity());
327 for (int sign = 0; sign < 2; ++sign) {
328 if (sign == 1) {
329 for (auto &v : reversed) {
330 v = -v;
331 }
332 child.setBeads(beads);
333 child.setMomenta(reversed);
334 }
335 const double sdot = sign == 0 ? forward : -forward;
336 const double flux = sdot > 0.0 ? sdot : 0.0;
337 den += flux;
338 num(0) += flux;
339 for (long i = 1; i < n; ++i) {
340 child.nveStep(pot, c.box);
341 const double s = ax.a.dot(child.centroid() - c.reference);
342 if (s > o.s) {
343 num(i) += sdot;
344 }
345 }
346 ++out.trajectories;
347 }
348 }
349 }
350
351 VectorXd total = VectorXd::Zero(n);
352 double totalDen = 0.0;
353 for (long p = 0; p < o.parents; ++p) {
354 total += numerator[static_cast<size_t>(p)];
355 totalDen += denominator[static_cast<size_t>(p)];
356 }
357 if (!(totalDen > 0.0)) {
358 throw std::runtime_error("piqtst: no child left the plane forward");
359 }
360 out.time.resize(static_cast<size_t>(n));
361 out.kappa.resize(static_cast<size_t>(n));
362 for (long i = 0; i < n; ++i) {
363 out.time[static_cast<size_t>(i)] = static_cast<double>(i) * o.ring.dt;
364 out.kappa[static_cast<size_t>(i)] = total(i) / totalDen;
365 }
366
367 // Plateau numerators per parent, averaged over the last quarter, and the
368 // leave-one-parent-out ratios.
369 const long first = n - 1 - o.steps / 4;
370 const double span = static_cast<double>(n - first);
371 std::vector<double> plateauNum(static_cast<size_t>(o.parents), 0.0);
372 double sumNum = 0.0;
373 for (long p = 0; p < o.parents; ++p) {
374 plateauNum[static_cast<size_t>(p)] =
375 numerator[static_cast<size_t>(p)].tail(n - first).sum() / span;
376 sumNum += plateauNum[static_cast<size_t>(p)];
377 }
378 out.plateau = sumNum / totalDen;
379 const double np = static_cast<double>(o.parents);
380 std::vector<double> leaveOut(static_cast<size_t>(o.parents), 0.0);
381 double meanLeave = 0.0;
382 for (long p = 0; p < o.parents; ++p) {
383 leaveOut[static_cast<size_t>(p)] =
384 (sumNum - plateauNum[static_cast<size_t>(p)]) /
385 (totalDen - denominator[static_cast<size_t>(p)]);
386 meanLeave += leaveOut[static_cast<size_t>(p)];
387 }
388 meanLeave /= np;
389 double var = 0.0;
390 for (const double v : leaveOut) {
391 var += (v - meanLeave) * (v - meanLeave);
392 }
393 out.plateauError = std::sqrt((np - 1.0) / np * var);
394 out.batches = parent.batches() + child.batches();
395 return out;
396}
397
398} // namespace eonc::piqtst
Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic, eOnStorageOrder > MatrixXd
Definition Eigen.h:33
Ring-polymer NVT step.
void setAllBeads(const double *q)
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.
void setBeads(const std::vector< VectorXd > &beads)
One position vector of length 3 * nAtoms per bead.
void setHyperplane(const VectorXd &normal, const VectorXd &origin)
Hold n · (q_centroid - origin) = 0.
void step(Potential &pot, const double *box, bool record)
const std::vector< VectorXd > & momenta() const
const std::vector< VectorXd > & beads() const
Recrossing recrossing(Potential &pot, const Coordinate &c, const RecrossingOptions &o)
Bennett-Chandler transmission at s*: parents sampled with the centroid held on the plane under PILE,...
Definition PIQTST.cpp:266
std::vector< Plane > scan(Potential &pot, const Coordinate &c, const ScanOptions &o)
Samples one ring per plane and integrates the mean force.
Definition PIQTST.cpp:104
void integrate(std::vector< Plane > &planes)
Trapezoid integral of the mean forces, F(s_0) = 0, with errors from independent planes.
Definition PIQTST.cpp:86
Rate rate(const std::vector< Plane > &planes, double beta)
k = (1/2) sqrt(2 / (pi beta)) exp(-beta F(s*)) / int_{s_0}^{s*} exp(-beta F(s)) ds,...
Definition PIQTST.cpp:213
std::string gleFile
Normal-mode GLE matrices in normal-mode order.
The coordinate s = n .
Definition PIQTST.h:42
std::vector< char > free
Definition PIQTST.h:46
std::vector< int > numbers
Definition PIQTST.h:45
std::vector< double > masses
Definition PIQTST.h:44
const double * box
Definition PIQTST.h:49
double meanForceError
Definition PIQTST.h:76
std::vector< double > spread
Root-mean-square bead displacement from the centroid per Cartesian coordinate, Angstrom,...
Definition PIQTST.h:85
VectorXd centroid
Production average of the centroid, Cartesian.
Definition PIQTST.h:82
double meanForce
dF/ds = -<a . f_centroid> / |a|^2, a = M^(1/2) n the plane's Cartesian normal, eV / (amu^0....
Definition PIQTST.h:75
long reactant
Index of the plane with the lowest F before s*, the reactant.
Definition PIQTST.h:103
double barrierError
Definition PIQTST.h:107
double firstPlaneHeight
beta (F(s_0) - F(reactant)): the reactant integral is cut at s_0, so a small value means the first pl...
Definition PIQTST.h:114
double logRate
ln k with k in inverse eOn time units (sqrt(amu Angstrom^2 / eV)), and its standard error.
Definition PIQTST.h:110
double barrier
F(s*) - F(reactant), eV, and its error; not positive when s* is no barrier on the centroid free energ...
Definition PIQTST.h:106
double logRateError
Definition PIQTST.h:111
long parents
Parent configurations, each this many thermostatted steps after the last.
Definition PIQTST.h:130
long equilibration
Thermostatted steps on the plane before the first parent.
Definition PIQTST.h:127
std::function< VectorXd(double)> seed
Cartesian centroid to start the parent ring at.
Definition PIQTST.h:141
long steps
Unconstrained, thermostat-free steps per child of ring.dt.
Definition PIQTST.h:135
long children
Momentum draws per parent; each runs forward and reversed.
Definition PIQTST.h:133
double s
The dividing plane s*, amu^0.5 Angstrom.
Definition PIQTST.h:125
pathintegral::Options ring
The parents' ring and thermostat.
Definition PIQTST.h:138
std::vector< double > time
t = step * ring.dt, from 0 to steps * ring.dt, and kappa(t) = <sdot(0) h(s(t) - s*)> / <sdot(0) h(sdo...
Definition PIQTST.h:149
double plateau
Mean of kappa(t) over the last quarter of the times, and its jackknife standard error over parents.
Definition PIQTST.h:153
std::vector< double > kappa
Definition PIQTST.h:150
std::function< VectorXd(double)> seed
Cartesian centroid to start the ring at on the plane at s.
Definition PIQTST.h:65
std::vector< double > planes
Plane positions in amu^0.5 Angstrom, ascending.
Definition PIQTST.h:55
long blocks
Equal blocks of the production run for the standard error.
Definition PIQTST.h:59
pathintegral::Options ring
Beads, temperature, units (kB in eV / K, hbar in eV time units), time step and thermostat of the ring...
Definition PIQTST.h:62