Loading...
Searching...
No Matches
PotentialPath.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2#include "PotentialPath.h"
3
4#include <algorithm>
5#include <cmath>
6#include <stdexcept>
7#include <utility>
8
9#include "HarmonicReference.h"
11
12namespace gpr::quantum {
13namespace {
14using Vector = Eigen::VectorXd;
15using Matrix = Eigen::MatrixXd;
16using Nodes = std::vector<Vector>;
17void finiteVector(const Vector& value, Eigen::Index d)
18{
19 if (value.size() != d || !value.allFinite())
20 throw std::invalid_argument(
21 "Finite matching vector dimension required");
22}
23} // namespace
24
26 : origin_(std::move(origin))
27{
28 if (!masses.size() || masses.size() != origin_.size() ||
29 !masses.allFinite() || !origin_.allFinite() ||
30 (masses.array() <= 0).any())
31 throw std::invalid_argument(
32 "Finite positive masses and matching origin required");
33 roots_ = masses.array().sqrt().matrix();
34}
36{
37 finiteVector(q, dimension());
38 return origin_ + q.cwiseQuotient(roots_);
39}
41{
42 finiteVector(x, dimension());
43 return (x - origin_).cwiseProduct(roots_);
44}
46{
47 finiteVector(g, dimension());
48 return g.cwiseQuotient(roots_);
49}
51{
52 if (h.rows() != dimension() || h.cols() != dimension() || !h.allFinite())
53 throw std::invalid_argument(
54 "Finite matching Hessian dimension required");
55 return roots_.cwiseInverse().asDiagonal() * h *
56 roots_.cwiseInverse().asDiagonal();
57}
59 const Matrix& linear,
60 const Vector& translation)
61{
62 finiteVector(translation, m.dimension());
63 if (linear.rows() != m.dimension() || linear.cols() != m.dimension() ||
64 !linear.allFinite())
65 throw std::invalid_argument(
66 "Finite matching physical boundary required");
68 out.twist =
69 m.roots().asDiagonal() * linear * m.roots().cwiseInverse().asDiagonal();
70 out.offset =
71 m.roots().cwiseProduct(linear * m.origin() + translation - m.origin());
72 if ((out.twist.transpose() * out.twist -
73 Matrix::Identity(m.dimension(), m.dimension()))
74 .norm() > 1e-12 * m.dimension())
75 throw std::invalid_argument(
76 "Physical boundary must preserve the mass metric");
77 return out;
78}
79
81 const MassMetric& metric,
82 const PathPotential& potential,
83 const AffinePathBoundary& boundary,
84 const PathConstraints& constraints,
85 const PotentialPathOptions& options)
86{
87 const auto n = initial.size();
88 const Eigen::Index d = metric.dimension(), k = constraints.target.size();
89 if (!n || (!potential.evaluate && !potential.evaluateBatch) ||
90 !(options.duration > 0) || !std::isfinite(options.duration) ||
91 !(options.hbar > 0) || !std::isfinite(options.hbar) ||
92 !(options.forceTolerance > 0) ||
93 !std::isfinite(options.forceTolerance) ||
94 !(options.constraintTolerance > 0) ||
95 !std::isfinite(options.constraintTolerance) ||
96 !(options.linearTolerance > 0) ||
97 !std::isfinite(options.linearTolerance) || !(options.maximumStep > 0) ||
98 !std::isfinite(options.maximumStep) || !(options.hessianStep > 0) ||
99 !std::isfinite(options.hessianStep) ||
100 !std::isfinite(options.energyShift) || !options.maximumBacktracks ||
101 boundary.twist.rows() != d || boundary.twist.cols() != d ||
102 !boundary.twist.allFinite() ||
103 (boundary.twist.transpose() * boundary.twist - Matrix::Identity(d, d))
104 .norm() > 1e-12 * d)
105 throw std::invalid_argument(
106 "Invalid cyclic potential path configuration");
107 finiteVector(boundary.offset, d);
108 finiteVector(constraints.target, k);
109 std::vector<Matrix> normals = constraints.normals;
110 if (!k && normals.empty()) normals.assign(n, Matrix(d, 0));
111 if (normals.size() != n)
112 throw std::invalid_argument("One constraint block per node required");
113 Matrix gram = Matrix::Zero(k, k);
114 for (std::size_t j = 0; j < n; ++j) {
115 finiteVector(initial[j], d);
116 if (normals[j].rows() != d || normals[j].cols() != k ||
117 !normals[j].allFinite())
118 throw std::invalid_argument(
119 "Matching finite constraint blocks required");
120 gram += normals[j].transpose() * normals[j];
121 }
122 if ((gram - Matrix::Identity(k, k)).norm() >
123 1e-10 * std::max<Eigen::Index>(1, k))
124 throw std::invalid_argument(
125 "Global constraint columns must be orthonormal");
126 const double h = options.duration / n;
127 if (!(h > 0) || !std::isfinite(h))
128 throw std::invalid_argument("Finite positive time step required");
129 const bool split = options.harmonicReferenceHessian.size() != 0;
130 const Matrix referenceHessian =
131 split ? options.harmonicReferenceHessian : Matrix::Zero(d, d);
132 if (referenceHessian.rows() != d || referenceHessian.cols() != d)
133 throw std::invalid_argument(
134 "Harmonic reference must match the mass dimension");
135 const HarmonicReference reference(referenceHessian, h,
137 PotentialPathResult result;
138 result.path = initial;
139 auto coordinate = [&](const Nodes& p) {
140 Vector value = -constraints.target;
141 for (std::size_t j = 0; j < n; ++j)
142 value += normals[j].transpose() * p[j];
143 return value;
144 };
145 auto enforce = [&](Nodes& p) {
146 const Vector error = coordinate(p);
147 for (std::size_t j = 0; j < n; ++j)
148 p[j] -= normals[j] * error;
149 };
150 enforce(result.path);
151 auto checkedPoint = [&](PotentialEvaluation value) {
152 if (!std::isfinite(value.energy))
153 throw std::runtime_error("Potential energy is not finite");
154 value.gradient = metric.gradient(value.gradient);
155 return value;
156 };
157 auto point = [&](const Vector& q) {
158 ++result.evaluations;
159 if (potential.evaluate)
160 return checkedPoint(potential.evaluate(metric.physical(q)));
161 ++result.batchEvaluations;
162 const auto values = potential.evaluateBatch({metric.physical(q)});
163 if (values.size() != 1)
164 throw std::runtime_error(
165 "Potential batch returned the wrong number of points");
166 return checkedPoint(values.front());
167 };
168 struct State {
169 Nodes gradient, full, conditional;
170 std::vector<double> energies;
171 Vector normal, endpointGradient;
172 double endpointEnergy = 0;
173 double action = 0, fullForce = 0, conditionalForce = 0, constraint = 0;
174 };
175 auto evaluate = [&](const Nodes& p) {
176 State state;
177 state.normal = Vector::Zero(k);
178 std::vector<PotentialEvaluation> values;
179 const Vector endpointCoordinate =
180 boundary.twist * p.front() + boundary.offset;
181 if (potential.evaluateBatch) {
182 Nodes physical;
183 for (const auto& q: p)
184 physical.push_back(metric.physical(q));
185 physical.push_back(metric.physical(endpointCoordinate));
186 result.evaluations += physical.size();
187 ++result.batchEvaluations;
188 values = potential.evaluateBatch(physical);
189 if (values.size() != physical.size())
190 throw std::runtime_error(
191 "Potential batch returned the wrong number of points");
192 for (auto& value: values)
193 value = checkedPoint(std::move(value));
194 } else {
195 for (const auto& q: p)
196 values.push_back(point(q));
197 values.push_back(point(endpointCoordinate));
198 }
199 for (std::size_t j = 0; j < n; ++j) {
200 const auto& value = values[j];
201 state.energies.push_back(value.energy);
202 state.full.push_back(value.gradient);
203 }
204 const auto& endpoint = values.back();
205 state.endpointEnergy = endpoint.energy;
206 state.endpointGradient = endpoint.gradient;
207 if (split) {
208 const Nodes gradients = state.full;
209 state.full.assign(n, Vector::Zero(d));
210 for (std::size_t j = 0; j < n; ++j) {
211 const bool closing = j + 1 == n;
212 const Vector next =
213 closing
214 ? Vector(boundary.twist * p.front() + boundary.offset)
215 : p[j + 1];
216 const PotentialEvaluation left{state.energies[j], gradients[j]};
217 const PotentialEvaluation right =
218 closing ? endpoint
219 : PotentialEvaluation{state.energies[j + 1],
220 gradients[j + 1]};
221 const auto link = reference.evaluate(p[j], next, left, right,
222 options.energyShift);
223 state.action += link.action;
224 state.full[j] += link.leftGradient / h;
225 if (closing)
226 state.full[0] +=
227 boundary.twist.transpose() * link.rightGradient / h;
228 else
229 state.full[j + 1] += link.rightGradient / h;
230 }
231 for (std::size_t j = 0; j < n; ++j) {
232 state.gradient.push_back(h * state.full[j]);
233 state.normal += normals[j].transpose() * state.full[j];
234 state.fullForce =
235 std::max(state.fullForce, state.full[j].norm());
236 }
237 } else {
238 state.full[0] = .5 * (state.full[0] + boundary.twist.transpose() *
239 endpoint.gradient);
240 for (std::size_t j = 0; j < n; ++j) {
241 const Vector previous =
242 j ? p[j - 1]
243 : Vector(boundary.twist.transpose() *
244 (p.back() - boundary.offset));
245 const Vector next =
246 j + 1 < n
247 ? p[j + 1]
248 : Vector(boundary.twist * p.front() + boundary.offset);
249 state.full[j] += (2 * p[j] - previous - next) / (h * h);
250 state.gradient.push_back(h * state.full[j]);
251 state.normal += normals[j].transpose() * state.full[j];
252 state.fullForce =
253 std::max(state.fullForce, state.full[j].norm());
254 state.action += h * (state.energies[j] - options.energyShift) +
255 (next - p[j]).squaredNorm() / (2 * h);
256 }
257 state.action += .5 * h * (endpoint.energy - state.energies[0]);
258 }
259 for (std::size_t j = 0; j < n; ++j) {
260 state.conditional.push_back(state.full[j] -
261 normals[j] * state.normal);
262 state.conditionalForce = std::max(state.conditionalForce,
263 state.conditional.back().norm());
264 }
265 state.constraint = coordinate(p).norm();
266 if (!std::isfinite(state.action) || !std::isfinite(state.fullForce) ||
267 !std::isfinite(state.conditionalForce))
268 throw std::runtime_error("Path action or residual is not finite");
269 return state;
270 };
271 auto pointHessian = [&](const Vector& q, bool search) {
272 Matrix physical(d, d);
273 const bool approximate = search && bool(potential.searchHessian);
274 if (approximate)
276 else
277 ++result.hessianEvaluations;
278 const auto& callback =
279 approximate ? potential.searchHessian : potential.hessian;
280 if (callback) {
281 physical = metric.hessian(callback(metric.physical(q)));
282 const double defect = (physical - physical.transpose()).norm();
283 if (defect > 1e-10 * std::max(1., physical.norm()))
284 throw std::runtime_error(
285 "Potential curvature callback is not symmetric");
286 } else
287 for (Eigen::Index axis = 0; axis < d; ++axis) {
288 Vector plus = q, minus = q;
289 plus[axis] += options.hessianStep;
290 minus[axis] -= options.hessianStep;
291 const Vector gp = point(plus).gradient,
292 gm = point(minus).gradient;
293 physical.col(axis) = (gp - gm) / (2 * options.hessianStep);
294 }
296 std::max(result.maximumHessianAsymmetry,
297 (physical - physical.transpose()).norm());
298 return Matrix(.5 * (physical + physical.transpose()));
299 };
300 auto segments = [&](const Nodes& p, bool search) {
301 std::vector<Matrix> hessians;
302 for (const auto& q: p)
303 hessians.push_back(pointHessian(q, search));
304 hessians.push_back(
305 pointHessian(boundary.twist * p.front() + boundary.offset, search));
306 std::vector<gaussian::Segment> out;
307 for (std::size_t j = 0; j < n; ++j)
308 out.push_back(reference.quadratic(hessians[j], hessians[j + 1]));
309 return out;
310 };
311 auto blocks = [&](const Nodes& p) {
312 if (split) {
313 const auto links = segments(p, true);
314 std::vector<Matrix> out;
315 out.push_back(links.front().A + boundary.twist.transpose() *
316 links.back().rightEndpoint() *
317 boundary.twist);
318 for (std::size_t j = 1; j < n; ++j)
319 out.push_back(links[j - 1].rightEndpoint() + links[j].A);
320 return out;
321 }
322 std::vector<Matrix> out;
323 for (const auto& q: p)
324 out.push_back(pointHessian(q, true));
325 const Matrix endpoint =
326 pointHessian(boundary.twist * p.front() + boundary.offset, true);
327 out[0] = .5 * (out[0] +
328 boundary.twist.transpose() * endpoint * boundary.twist);
329 for (auto& block: out)
330 block = h * block + (2 / h) * Matrix::Identity(d, d);
331 return out;
332 };
333 State state;
334 bool hasState = false;
335 auto metricResidual = [&](const State& s) {
336 return options.requireFullStationarity ? s.fullForce
337 : s.conditionalForce;
338 };
339 auto record = [&](const TwistedConstraintStep* solved) {
340 PathIteration item;
341 item.iteration = result.iterations;
342 item.evaluations = result.evaluations;
346 item.action = state.action;
347 item.fullForce = state.fullForce;
348 item.conditionalForce = state.conditionalForce;
349 item.constraintResidual = state.constraint;
350 item.normalForces = state.normal;
351 if (solved) {
352 item.multipliers = solved->multipliers;
353 item.linearResidual = solved->relativeResidual;
354 item.linearConstraintResidual = solved->constraintResidual;
355 }
356 result.history.push_back(std::move(item));
357 };
358 try {
359 state = evaluate(result.path);
360 hasState = true;
361 record(nullptr);
362 while (metricResidual(state) > options.forceTolerance &&
363 result.iterations < options.maximumIterations) {
364 ++result.iterations;
365 const auto solved = solveTwistedConstraints(
366 blocks(result.path), state.gradient, normals,
367 reference.kernel().L, boundary.twist, -coordinate(result.path));
368 if (!solved.invertible ||
369 solved.relativeResidual > options.linearTolerance ||
370 solved.constraintResidual > options.constraintTolerance) {
371 record(&solved);
372 result.failure =
373 "Constrained cyclic Newton solve fails its residual checks";
374 break;
375 }
376 double maximum = 0;
377 for (const auto& v: solved.displacement)
378 maximum = std::max(maximum, v.norm());
379 double scale = maximum > options.maximumStep
380 ? options.maximumStep / maximum
381 : 1.;
382 bool accepted = false;
383 for (std::size_t trial = 0; trial < options.maximumBacktracks;
384 ++trial, scale *= .5) {
385 Nodes candidate = result.path;
386 for (std::size_t j = 0; j < n; ++j)
387 candidate[j] += scale * solved.displacement[j];
388 enforce(candidate);
389 State next = evaluate(candidate);
390 if (metricResidual(next) < metricResidual(state) &&
391 next.constraint <= options.constraintTolerance) {
392 result.path = std::move(candidate);
393 state = std::move(next);
394 ++result.acceptedSteps;
395 accepted = true;
396 record(&solved);
397 break;
398 }
399 }
400 if (!accepted) {
401 record(&solved);
402 result.failure =
403 "Path residual does not decrease on the supplied affine "
404 "slice";
405 break;
406 }
407 }
408 } catch (const std::exception& error) {
409 result.failure = error.what();
410 }
411 for (const auto& q: result.path)
412 result.physicalPath.push_back(metric.physical(q));
413 if (hasState) {
414 result.action = state.action;
415 result.actionOverHbar = state.action / options.hbar;
416 result.energies = state.energies;
417 result.endpointEnergy = state.endpointEnergy;
418 result.endpointGradient = state.endpointGradient;
419 result.fullGradient = state.full;
420 result.conditionalGradient = state.conditional;
421 result.normalForces = state.normal;
422 result.fullForce = state.fullForce;
423 result.conditionalForce = state.conditionalForce;
424 result.constraintResidual = state.constraint;
426 state.fullForce <= options.forceTolerance &&
427 state.constraint <= options.constraintTolerance;
429 state.conditionalForce <= options.forceTolerance &&
430 state.constraint <= options.constraintTolerance;
431 result.converged = options.requireFullStationarity
434 if (!result.converged && result.failure.empty())
435 result.failure = "Maximum path iterations reached";
436 if (options.retainQuadratic) {
437 try {
438 result.fluctuationSegments = segments(result.path, false);
439 } catch (const std::exception& error) {
440 result.failure = error.what();
441 result.converged = false;
442 }
443 }
444 }
445 return result;
446}
447} // namespace gpr::quantum
@ x
Definition Enums.h:28
gaussian::Segment quadratic(const Eigen::MatrixXd &leftHessian, const Eigen::MatrixXd &rightHessian) const
const gaussian::Segment & kernel() const
HarmonicLinkEvaluation evaluate(const Eigen::VectorXd &left, const Eigen::VectorXd &right, const PotentialEvaluation &leftPotential, const PotentialEvaluation &rightPotential, double energyShift=0) const
const Eigen::VectorXd & roots() const noexcept
MassMetric(Eigen::VectorXd masses, Eigen::VectorXd origin)
Eigen::VectorXd gradient(const Eigen::VectorXd &physicalGradient) const
Eigen::VectorXd physical(const Eigen::VectorXd &q) const
Eigen::VectorXd weighted(const Eigen::VectorXd &x) const
Eigen::MatrixXd hessian(const Eigen::MatrixXd &physicalHessian) const
Eigen::Index dimension() const noexcept
const Eigen::VectorXd & origin() const noexcept
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
Models for quantum-path (instanton) searches: arc and tail actions, amplitude continuation.
Eigen::MatrixXd Matrix
Eigen::VectorXd Vector
PotentialPathResult optimizePotentialPath(const Nodes &initial, const MassMetric &metric, const PathPotential &potential, const AffinePathBoundary &boundary, const PathConstraints &constraints, const PotentialPathOptions &options)
AffinePathBoundary physicalPathBoundary(const MassMetric &m, const Matrix &linear, const Vector &translation)
TwistedConstraintStep solveTwistedConstraints(const std::vector< Eigen::MatrixXd > &diagonal, const std::vector< Eigen::VectorXd > &gradient, const std::vector< Eigen::MatrixXd > &normals, double coupling, const Eigen::MatrixXd &twist, const Eigen::VectorXd &correction)
STL namespace.
std::vector< Eigen::MatrixXd > normals
std::function< Eigen::MatrixXd(const Eigen::VectorXd &)> searchHessian
std::function< std::vector< PotentialEvaluation >(const std::vector< Eigen::VectorXd > &)> evaluateBatch
std::function< Eigen::MatrixXd(const Eigen::VectorXd &)> hessian
std::function< PotentialEvaluation(const Eigen::VectorXd &)> evaluate
ReferenceDiscretization referenceDiscretization
std::vector< Eigen::VectorXd > fullGradient
std::vector< Eigen::VectorXd > conditionalGradient
std::vector< Eigen::VectorXd > physicalPath
std::vector< gaussian::Segment > fluctuationSegments
std::vector< Eigen::VectorXd > path
std::vector< PathIteration > history