Loading...
Searching...
No Matches
ConstrainedImaginaryTimePath.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
6#pragma once
7#include <Eigen/Cholesky>
8#include <algorithm>
9#include <cmath>
10#include <functional>
11#include <stdexcept>
12#include <string>
13#include <utility>
14#include <vector>
15
17
18namespace gpr::quantum {
19
21 double time{};
23 double pathVelocity{};
24 Eigen::VectorXd position;
25 Eigen::VectorXd velocity;
26};
27
29 std::vector<ConstrainedImaginaryTimeSample> samples;
30 double halfPeriod{};
31 double period{};
32 double temperature{};
34 std::string turningPointEvent;
36};
37
39 std::vector<Eigen::VectorXd> path;
40 std::size_t energyEvaluations{};
44};
45
46// Project both path ends onto the common energy contour before constructing
47// the periodic orbit. The instanton energy integral requires equal turning
48// energies at the two ends.
49template <class NativeEvaluate, class NativeEnergy>
51 const std::vector<Eigen::VectorXd>& cartesianPath, double contourEnergy,
52 NativeEvaluate&& evaluate, NativeEnergy&& nativeEnergy,
53 std::size_t maximumIterations = 32, double maximumStepBohr = .1,
54 double energyTolerance = 1e-12)
55{
56 using V = Eigen::VectorXd;
57 if (cartesianPath.size() < 3 || !std::isfinite(contourEnergy) ||
58 !maximumIterations || !(maximumStepBohr > 0) ||
59 !std::isfinite(maximumStepBohr) || !(energyTolerance > 0) ||
60 !std::isfinite(energyTolerance))
61 throw std::invalid_argument(
62 "Finite contour energy and turning-point controls required");
64 result.path = cartesianPath;
65 for (const auto endpoint: {std::size_t{0}, result.path.size() - 1}) {
66 V& x = result.path[endpoint];
67 const V initial = x;
68 for (std::size_t iteration = 0; iteration < maximumIterations;
69 ++iteration) {
70 const double residual = nativeEnergy(x) - contourEnergy;
71 ++result.energyEvaluations;
72 result.initialMaximumEnergyResidual = std::max(
73 result.initialMaximumEnergyResidual, std::abs(residual));
74 if (std::abs(residual) <= energyTolerance) break;
75 const auto value = evaluate(x);
76 if (value.gradient.size() != x.size() ||
77 !value.gradient.allFinite())
78 throw std::runtime_error(
79 "Native turning-point gradient has the wrong shape");
80 const double norm2 = value.gradient.squaredNorm();
81 if (!(norm2 > 0) || !std::isfinite(norm2))
82 throw std::domain_error("Turning contour has no finite normal");
83 V step = (-residual / norm2) * value.gradient;
84 if (step.norm() > maximumStepBohr)
85 step *= maximumStepBohr / step.norm();
86 bool accepted = false;
87 for (double scale = 1.; scale >= 1. / 256.; scale *= .5) {
88 const V candidate = x + scale * step;
89 const double candidateResidual =
90 nativeEnergy(candidate) - contourEnergy;
91 ++result.energyEvaluations;
92 if (std::abs(candidateResidual) < std::abs(residual)) {
93 x = candidate;
94 accepted = true;
95 break;
96 }
97 }
98 if (!accepted)
99 throw std::runtime_error(
100 "Turning-point contour projection stalled");
101 }
102 const double residual = std::abs(nativeEnergy(x) - contourEnergy);
103 ++result.energyEvaluations;
104 result.maximumEnergyResidual =
105 std::max(result.maximumEnergyResidual, residual);
106 result.maximumDisplacement =
107 std::max(result.maximumDisplacement, (x - initial).norm());
108 if (residual > energyTolerance)
109 throw std::runtime_error(
110 "Turning point did not reach the common energy contour");
111 }
112 return result;
113}
114
116public:
117 using V = Eigen::VectorXd;
118
119private:
120 std::vector<double> knots_;
121 std::vector<V> values_;
122 std::vector<V> second_;
123
124public:
125 explicit CartesianNaturalCubicPath(const std::vector<V>& path)
126 : values_(path)
127 {
128 if (path.size() < 3)
129 throw std::invalid_argument(
130 "Cartesian spline requires at least three path nodes");
131 knots_.resize(path.size());
132 knots_[0] = 0.;
133 for (std::size_t j = 1; j < path.size(); ++j) {
134 if (path[j].size() != path.front().size() || !path[j].allFinite())
135 throw std::invalid_argument(
136 "Finite consistent Cartesian path coordinates required");
137 const double length = (path[j] - path[j - 1]).norm();
138 if (!(length > 0) || !std::isfinite(length))
139 throw std::invalid_argument(
140 "Distinct Cartesian path nodes required");
141 knots_[j] = knots_[j - 1] + length;
142 }
143 const double total = knots_.back();
144 if (!(total > 0) || !std::isfinite(total))
145 throw std::invalid_argument(
146 "Finite Cartesian path length required");
147 for (double& knot: knots_)
148 knot /= total;
149 second_.assign(path.size(), V::Zero(path.front().size()));
150 const Eigen::Index interior =
151 static_cast<Eigen::Index>(path.size() - 2);
152 Eigen::MatrixXd matrix = Eigen::MatrixXd::Zero(interior, interior);
153 Eigen::MatrixXd rhs =
154 Eigen::MatrixXd::Zero(interior, path.front().size());
155 for (Eigen::Index i = 0; i < interior; ++i) {
156 const std::size_t j = static_cast<std::size_t>(i + 1);
157 const double left = knots_[j] - knots_[j - 1],
158 right = knots_[j + 1] - knots_[j];
159 matrix(i, i) = 2 * (left + right);
160 if (i) matrix(i, i - 1) = left;
161 if (i + 1 < interior) matrix(i, i + 1) = right;
162 rhs.row(i) = 6 * ((path[j + 1] - path[j]) / right -
163 (path[j] - path[j - 1]) / left)
164 .transpose();
165 }
166 const Eigen::MatrixXd curvature = matrix.ldlt().solve(rhs);
167 if (!curvature.allFinite())
168 throw std::runtime_error("Cartesian natural spline solve failed");
169 for (Eigen::Index i = 0; i < interior; ++i)
170 second_[static_cast<std::size_t>(i + 1)] =
171 curvature.row(i).transpose();
172 }
173
174 std::pair<V, V> evaluate(double r) const
175 {
176 if (!std::isfinite(r))
177 throw std::invalid_argument(
178 "Finite Cartesian path coordinate required");
179 auto upper = std::upper_bound(knots_.begin(), knots_.end(), r);
180 std::size_t i =
181 upper == knots_.begin() ? 0
182 : upper == knots_.end()
183 ? knots_.size() - 2
184 : static_cast<std::size_t>(upper - knots_.begin() - 1);
185 const double h = knots_[i + 1] - knots_[i], z = r - knots_[i];
186 const V b = (values_[i + 1] - values_[i]) / h -
187 h * (2 * second_[i] + second_[i + 1]) / 6.;
188 const V c = second_[i] / 2.;
189 const V d = (second_[i + 1] - second_[i]) / (6 * h);
190 return {values_[i] + z * (b + z * (c + z * d)),
191 b + z * (2 * c + 3 * z * d)};
192 }
193
194 std::pair<V, V> derivatives(double r) const
195 {
196 if (!std::isfinite(r))
197 throw std::invalid_argument(
198 "Finite Cartesian path coordinate required");
199 auto upper = std::upper_bound(knots_.begin(), knots_.end(), r);
200 std::size_t i =
201 upper == knots_.begin() ? 0
202 : upper == knots_.end()
203 ? knots_.size() - 2
204 : static_cast<std::size_t>(upper - knots_.begin() - 1);
205 const double h = knots_[i + 1] - knots_[i], z = r - knots_[i];
206 const V b = (values_[i + 1] - values_[i]) / h -
207 h * (2 * second_[i] + second_[i + 1]) / 6.;
208 const V c = second_[i] / 2.;
209 const V d = (second_[i + 1] - second_[i]) / (6 * h);
210 return {b + z * (2 * c + 3 * z * d), 2 * c + 6 * z * d};
211 }
212};
213
214// Integrates constrained Newton motion on the natural cubic Cartesian spline
215// under the inverted physical potential. Coordinates and masses use atomic
216// units.
217template <class NativeEvaluate, class NativeEnergy>
219 const std::vector<Eigen::VectorXd>& cartesianPath,
220 const Eigen::VectorXd& masses, NativeEvaluate&& evaluate,
221 NativeEnergy&& nativeEnergy, double timeStep = 4.,
222 double boltzmann = 3.1668152e-6, std::size_t maximumSteps = 1000000,
223 double endTolerance = 1e-3)
224{
225 using V = Eigen::VectorXd;
226 if (masses.size() < 9 || masses.size() % 3 || !masses.allFinite() ||
227 !(masses.array() > 0).all() || !(timeStep > 0) ||
228 !std::isfinite(timeStep) || !(boltzmann > 0) ||
229 !std::isfinite(boltzmann) || !maximumSteps || !(endTolerance > 0) ||
230 !std::isfinite(endTolerance))
231 throw std::invalid_argument(
232 "Finite masses and imaginary-time integration controls required");
233 for (const auto& x: cartesianPath)
234 if (x.size() != masses.size() || !x.allFinite())
235 throw std::invalid_argument(
236 "Cartesian path and mass dimensions differ");
237 CartesianNaturalCubicPath spline(cartesianPath);
238 struct State {
239 double r{}, v{};
240 };
241 auto rhs = [&](const State& y) {
242 const auto [x, dx] = spline.evaluate(y.r);
243 const auto [unused, d2x] = spline.derivatives(y.r);
244 (void)unused;
245 const auto value = evaluate(x);
246 if (value.gradient.size() != masses.size() ||
247 !value.gradient.allFinite())
248 throw std::runtime_error(
249 "Native imaginary-time path gradient has the wrong shape");
250 const double metric = dx.dot(masses.cwiseProduct(dx));
251 if (!(metric > 0) || !std::isfinite(metric))
252 throw std::domain_error("Cartesian spline has zero mass speed");
253 const double force = dx.dot(value.gradient);
254 const double curvature = dx.dot(masses.cwiseProduct(d2x));
255 const double acceleration = (force - curvature * y.v * y.v) / metric;
256 if (!std::isfinite(acceleration))
257 throw std::runtime_error(
258 "Nonfinite constrained imaginary-time acceleration");
259 return State{y.v, acceleration};
260 };
261 auto add = [](const State& a, const State& b, double scale) {
262 return State{a.r + scale * b.r, a.v + scale * b.v};
263 };
264 auto advance = [&](const State& y, double dt) {
265 const State k1 = rhs(y), k2 = rhs(add(y, k1, .5 * dt));
266 const State k3 = rhs(add(y, k2, .5 * dt)), k4 = rhs(add(y, k3, dt));
267 return State{y.r + dt * (k1.r + 2 * k2.r + 2 * k3.r + k4.r) / 6.,
268 y.v + dt * (k1.v + 2 * k2.v + 2 * k3.v + k4.v) / 6.};
269 };
271 State state{0., 0.};
272 double time = 0.;
273 const auto [x0, dx0] = spline.evaluate(0.);
274 (void)dx0;
275 const double energy0 = -nativeEnergy(x0);
276 result.samples.push_back(
277 {time, state.r, state.v, x0, V::Zero(masses.size())});
278 bool reachedTurningPoint = false;
279 for (std::size_t step = 0; step < maximumSteps; ++step) {
280 double acceptedStep = timeStep;
281 State next = advance(state, timeStep);
282 if (state.v > 0. && next.v <= 0.) {
283 double low = 0., high = timeStep;
284 for (int iteration = 0; iteration < 64; ++iteration) {
285 const double middle = .5 * (low + high);
286 if (advance(state, middle).v > 0.)
287 low = middle;
288 else
289 high = middle;
290 }
291 acceptedStep = .5 * (low + high);
292 next = advance(state, acceptedStep);
293 result.turningPointCoordinateCorrection = std::abs(next.r - 1.);
294 if (result.turningPointCoordinateCorrection > endTolerance)
295 throw std::runtime_error(
296 "Imaginary-time velocity reversal lies away from the "
297 "opposite turning point");
298 next.r = 1.;
299 next.v = 0.;
300 result.turningPointEvent = "velocity-reversal";
301 reachedTurningPoint = true;
302 }
303 state = next;
304 time += acceptedStep;
305 const auto [x, dx] = spline.evaluate(state.r);
306 const double energy = nativeEnergy(x);
307 const double kinetic =
308 .5 * state.v * state.v * dx.dot(masses.cwiseProduct(dx));
309 result.maximumEnergyDrift = std::max(
310 result.maximumEnergyDrift, std::abs(kinetic - energy - energy0));
311 result.samples.push_back({time, state.r, state.v, x, dx * state.v});
312 if (reachedTurningPoint) break;
313 }
314 if (!reachedTurningPoint)
315 throw std::runtime_error(
316 "Imaginary-time trajectory did not reach the opposite turning "
317 "point");
318 result.halfPeriod = time;
319 result.period = 2 * time;
320 result.temperature = 1. / (boltzmann * result.period);
321 if (!(result.period > 0) || !std::isfinite(result.temperature))
322 throw std::runtime_error(
323 "Imaginary-time trajectory has an invalid period");
324 return result;
325}
326
327inline std::vector<Eigen::VectorXd> sampleBondCenteredImaginaryTimeRing(
328 const ConstrainedImaginaryTimeTrajectory& trajectory, std::size_t fullBeads)
329{
330 if (fullBeads < 4 || fullBeads % 2 || trajectory.samples.size() < 2 ||
331 !(trajectory.period > 0) || !std::isfinite(trajectory.period))
332 throw std::invalid_argument(
333 "Even full ring and complete imaginary-time trajectory required");
334 const std::size_t halfBeads = fullBeads / 2;
335 std::vector<Eigen::VectorXd> half(halfBeads);
336 std::size_t segment = 0;
337 for (std::size_t bead = 0; bead < halfBeads; ++bead) {
338 const double target =
339 trajectory.period * (double(bead) + .5) / double(fullBeads);
340 while (segment + 1 < trajectory.samples.size() &&
341 target >= trajectory.samples[segment + 1].time)
342 ++segment;
343 if (segment + 1 >= trajectory.samples.size())
344 throw std::out_of_range(
345 "Ring time lies beyond the imaginary-time trajectory");
346 const auto& a = trajectory.samples[segment];
347 const auto& b = trajectory.samples[segment + 1];
348 const double dt = b.time - a.time, tau = target - a.time,
349 fraction = tau / dt;
350 half[bead] =
351 a.position + a.velocity * tau +
352 fraction * fraction * (b.position - a.position - a.velocity * dt);
353 }
354 std::vector<Eigen::VectorXd> ring(fullBeads);
355 for (std::size_t bead = 0; bead < halfBeads; ++bead) {
356 ring[bead] = half[bead];
357 ring[fullBeads - 1 - bead] = half[bead];
358 }
359 return ring;
360}
361
362} // namespace gpr::quantum
@ z
Definition Enums.h:28
@ x
Definition Enums.h:28
@ y
Definition Enums.h:28
Models for quantum-path (instanton) searches: arc and tail actions, amplitude continuation.
ConstrainedImaginaryTimeTrajectory integrateConstrainedImaginaryTimePath(const std::vector< Eigen::VectorXd > &cartesianPath, const Eigen::VectorXd &masses, NativeEvaluate &&evaluate, NativeEnergy &&nativeEnergy, double timeStep=4., double boltzmann=3.1668152e-6, std::size_t maximumSteps=1000000, double endTolerance=1e-3)
IsoenergyTurningPointRefinement refineIsoenergyTurningPoints(const std::vector< Eigen::VectorXd > &cartesianPath, double contourEnergy, NativeEvaluate &&evaluate, NativeEnergy &&nativeEnergy, std::size_t maximumIterations=32, double maximumStepBohr=.1, double energyTolerance=1e-12)
std::vector< Eigen::VectorXd > sampleBondCenteredImaginaryTimeRing(const ConstrainedImaginaryTimeTrajectory &trajectory, std::size_t fullBeads)
std::vector< ConstrainedImaginaryTimeSample > samples