Loading...
Searching...
No Matches
ReflectedPotentialPath.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
6#pragma once
7#include <Eigen/LU>
8#include <algorithm>
9#include <chrono>
10#include <cmath>
11#include <limits>
12#include <optional>
13#include <stdexcept>
14
18namespace gpr::quantum {
19// The cache owns only GP search algebra. Native forces and Jacobian actions
20// are evaluated at every path. Invalidate it when replacing callbacks inside
21// the same PathPotential owner or changing their physical interpretation.
23 using V = Eigen::VectorXd;
24 using M = Eigen::MatrixXd;
25 M normals_;
26 SearchKktFactor<> factor_;
27 V roots_, origin_, target_;
28 const PathPotential* owner_{};
29 std::size_t nodes_{}, factorizations_{}, reuses_{}, probes_{},
30 acceptedProbes_{}, reusedProbes_{}, solves_{}, meritSolves_{};
31 double assemblySeconds_{}, factorizationSeconds_{}, solveSeconds_{},
32 meritAlgebraSeconds_{};
33 Eigen::Index dimension_{};
34 double duration_{}, differenceStep_{};
35 bool keyed_{}, refresh_{true};
36
37public:
39 {
40 factor_.clear();
41 refresh_ = true;
42 }
43 void useSparseSolver(bool enabled)
44 {
45 if (enabled != factor_.sparseEnabled()) {
46 factor_.setSparseEnabled(enabled);
47 refresh_ = true;
48 }
49 }
50 bool sparseSolverEnabled() const noexcept
51 {
52 return factor_.sparseEnabled();
53 }
54 bool usingSparseSolver() const noexcept
55 {
56 return factor_.usingSparse();
57 }
58 std::size_t sparseFactorizations() const noexcept
59 {
60 return factor_.sparseFactorizations();
61 }
62 std::size_t sparseDenseFallbacks() const noexcept
63 {
64 return factor_.denseFallbacks();
65 }
66 std::size_t searchResidualChecks() const noexcept
67 {
68 return factor_.residualChecks();
69 }
70 double searchResidualCheckSeconds() const noexcept
71 {
72 return factor_.residualCheckSeconds();
73 }
74 const std::string& sparseFallbackReason() const noexcept
75 {
76 return factor_.fallbackReason();
77 }
78 std::size_t factorizations() const noexcept
79 {
80 return factorizations_;
81 }
82 std::size_t reuses() const noexcept
83 {
84 return reuses_;
85 }
86 std::size_t probes() const noexcept
87 {
88 return probes_;
89 }
90 std::size_t acceptedProbes() const noexcept
91 {
92 return acceptedProbes_;
93 }
94 std::size_t reusedProbes() const noexcept
95 {
96 return reusedProbes_;
97 }
98 std::size_t solves() const noexcept
99 {
100 return solves_;
101 }
102 std::size_t meritSolves() const noexcept
103 {
104 return meritSolves_;
105 }
106 double assemblySeconds() const noexcept
107 {
108 return assemblySeconds_;
109 }
110 double factorizationSeconds() const noexcept
111 {
112 return factorizationSeconds_;
113 }
114 double solveSeconds() const noexcept
115 {
116 return solveSeconds_;
117 }
118 double meritAlgebraSeconds() const noexcept
119 {
120 return meritAlgebraSeconds_;
121 }
122 void recordAssembly(double seconds) noexcept
123 {
124 assemblySeconds_ += seconds;
125 }
126 void recordMeritAlgebra(double seconds) noexcept
127 {
128 meritAlgebraSeconds_ += seconds;
129 ++meritSolves_;
130 }
131 void recordProbe() noexcept
132 {
133 ++probes_;
134 }
135 void recordProbeAcceptance() noexcept
136 {
137 ++acceptedProbes_;
138 }
139 void recordProbeReuse() noexcept
140 {
141 ++reusedProbes_;
142 }
143 bool needsRefresh() const noexcept
144 {
145 return refresh_ || factor_.matrix().size() == 0;
146 }
147 void requestRefresh(bool value = true) noexcept
148 {
149 refresh_ = value;
150 }
151 void bind(std::size_t nodes, const MassMetric& metric, const M& normals,
152 const V& target, double duration, double differenceStep,
153 const PathPotential& owner, double linearTolerance = 1e-8)
154 {
155 factor_.setTolerance(linearTolerance);
156 auto same = [](const auto& a, const auto& b) {
157 return a.rows() == b.rows() && a.cols() == b.cols() &&
158 (a.array() == b.array()).all();
159 };
160 const bool matches =
161 keyed_ && owner_ == &owner && nodes_ == nodes &&
162 dimension_ == metric.dimension() && duration_ == duration &&
163 differenceStep_ == differenceStep && same(roots_, metric.roots()) &&
164 same(origin_, metric.origin()) && same(normals_, normals) &&
165 same(target_, target);
166 if (matches) return;
167 invalidate();
168 nodes_ = nodes;
169 dimension_ = metric.dimension();
170 duration_ = duration;
171 differenceStep_ = differenceStep;
172 owner_ = &owner;
173 roots_ = metric.roots();
174 origin_ = metric.origin();
175 normals_ = normals;
176 target_ = target;
177 keyed_ = true;
178 }
179 void build(M matrix)
180 {
181 const auto begin = std::chrono::steady_clock::now();
182 factor_.compute(std::move(matrix));
183 factorizationSeconds_ += std::chrono::duration<double>(
184 std::chrono::steady_clock::now() - begin)
185 .count();
186 ++factorizations_;
187 refresh_ = false;
188 }
189 V solve(const V& rhs)
190 {
191 const auto begin = std::chrono::steady_clock::now();
192 V result = factor_.solve(rhs);
193 solveSeconds_ += std::chrono::duration<double>(
194 std::chrono::steady_clock::now() - begin)
195 .count();
196 ++solves_;
197 return result;
198 }
199 void reuse() noexcept
200 {
201 ++reuses_;
202 }
203 const M& matrix() const noexcept
204 {
205 return factor_.matrix();
206 }
207 // Explicit dense-factor access materializes the same KKT factor even
208 // when the selected search backend is sparse.
209 const Eigen::PartialPivLU<M>& factor() const
210 {
211 return factor_.denseFactor();
212 }
213};
214// Assess supplied physical values at the exact half-ring coordinates. No
215// projection or potential evaluation is performed; stationarity qualification
216// applies to these values and does not infer a physical rate.
218 const std::vector<Eigen::VectorXd>& halfMassPath, const MassMetric& metric,
219 const std::vector<PotentialEvaluation>& physicalValues,
220 const PathConstraints& gauge, const PotentialPathOptions& options = {})
221{
222 using V = Eigen::VectorXd;
223 using M = Eigen::MatrixXd;
224 const std::size_t m = halfMassPath.size();
225 const Eigen::Index d = metric.dimension(), nd = m * d,
226 k = gauge.target.size();
227 if (m < 2 || physicalValues.size() != m || !(options.duration > 0) ||
228 !std::isfinite(options.duration) || !(options.forceTolerance > 0) ||
229 !std::isfinite(options.forceTolerance) || !(options.maximumStep > 0) ||
230 !std::isfinite(options.maximumStep) || !options.maximumBacktracks ||
231 !(options.hbar > 0) || !std::isfinite(options.hbar) ||
232 !(options.hessianStep > 0) || !std::isfinite(options.hessianStep) ||
233 !(options.linearTolerance > 0) ||
234 !std::isfinite(options.linearTolerance) ||
235 !(options.constraintTolerance > 0) ||
236 !std::isfinite(options.constraintTolerance) ||
237 !std::isfinite(options.energyShift) ||
238 !(options.nativeJacobianProbeContraction >= 0 &&
239 options.nativeJacobianProbeContraction < 1) ||
240 !std::isfinite(options.nativeJacobianProbeContraction) ||
241 options.retainQuadratic || options.harmonicReferenceHessian.size() ||
242 !gauge.target.allFinite() || gauge.normals.size() != m)
243 throw std::invalid_argument(
244 "Reflected primitive path, supplied physical values and matching "
245 "rigid gauge required");
246 M normals(nd, k);
247 V path(nd);
248 for (std::size_t j = 0; j < m; ++j) {
249 if (halfMassPath[j].size() != d || !halfMassPath[j].allFinite() ||
250 gauge.normals[j].rows() != d || gauge.normals[j].cols() != k ||
251 !gauge.normals[j].allFinite() ||
252 !std::isfinite(physicalValues[j].energy) ||
253 physicalValues[j].gradient.size() != d ||
254 !physicalValues[j].gradient.allFinite())
255 throw std::invalid_argument(
256 "Finite matching reflected coordinates, physical values and "
257 "gauge blocks required");
258 path.segment(j * d, d) = halfMassPath[j];
259 // A zero-column matrix stores no data. middleRows at a nonzero row
260 // would offset that null pointer.
261 if (k > 0) normals.middleRows(j * d, d) = gauge.normals[j];
262 }
263 if ((normals.transpose() * normals - M::Identity(k, k)).norm() >
264 1e-10 * std::max<Eigen::Index>(1, k))
265 throw std::invalid_argument(
266 "Orthonormal reflected gauge columns required");
267 const double h = options.duration / (2 * m), spring = 1 / (h * h);
268 V gradient(nd);
269 PotentialPathResult result;
270 for (std::size_t j = 0; j < m; ++j) {
271 V g = metric.gradient(physicalValues[j].gradient);
272 if (j) g += spring * (halfMassPath[j] - halfMassPath[j - 1]);
273 if (j + 1 < m) g += spring * (halfMassPath[j] - halfMassPath[j + 1]);
274 gradient.segment(j * d, d) = g;
275 result.fullForce = std::max(result.fullForce, g.norm());
276 result.action +=
277 2 * h * (physicalValues[j].energy - options.energyShift);
278 if (j)
279 result.action +=
280 (halfMassPath[j] - halfMassPath[j - 1]).squaredNorm() / h;
281 }
282 result.actionOverHbar = result.action / options.hbar;
283 result.constraintResidual =
284 (normals.transpose() * path - gauge.target).norm();
285 result.normalForces = normals.transpose() * gradient;
286 if (!gradient.allFinite() || !std::isfinite(result.fullForce) ||
287 !std::isfinite(result.action) ||
288 !std::isfinite(result.actionOverHbar) ||
289 !std::isfinite(result.constraintResidual) ||
290 !result.normalForces.allFinite())
291 throw std::runtime_error("Nonfinite reflected path assessment");
292 result.converged = result.fullForce <= options.forceTolerance &&
293 result.constraintResidual <= options.constraintTolerance;
294 result.fullStationarityQualified = result.converged;
295 result.conditionalStationarityQualified = result.converged;
296 result.conditionalForce = result.fullForce;
297 if (!result.converged)
298 result.failure =
299 "Supplied reflected path does not satisfy force and gauge "
300 "tolerances";
301 for (std::size_t j = 0; j < 2 * m; ++j) {
302 const auto index = j < m ? j : 2 * m - 1 - j;
303 result.path.push_back(halfMassPath[index]);
304 result.physicalPath.push_back(metric.physical(halfMassPath[index]));
305 result.energies.push_back(physicalValues[index].energy);
306 result.fullGradient.push_back(gradient.segment(index * d, d));
307 }
308 result.conditionalGradient = result.fullGradient;
309 return result;
310}
311
312// A bond-centred time-reflection chart stores m nodes and reconstructs the
313// full ring as [q0,...,q(m-1),q(m-1),...,q0]. It fixes the phase by reflection,
314// retaining the physical unstable mode. Dense Newton supplies a molecular
315// reference; no rate or fluctuation determinant is inferred from convergence.
317 const std::vector<Eigen::VectorXd>& initial, const MassMetric& metric,
318 const PathPotential& potential, const PathConstraints& gauge,
319 const PotentialPathOptions& options = {},
320 ReflectedSearchCache* retainedSearch = nullptr)
321{
322 using V = Eigen::VectorXd;
323 using M = Eigen::MatrixXd;
324 const std::size_t m = initial.size();
325 const Eigen::Index d = metric.dimension(), nd = m * d,
326 k = gauge.target.size();
327 if (m < 2 || (!potential.evaluate && !potential.evaluateBatch) ||
328 !(options.duration > 0) || !std::isfinite(options.duration) ||
329 !(options.forceTolerance > 0) ||
330 !std::isfinite(options.forceTolerance) || !(options.maximumStep > 0) ||
331 !std::isfinite(options.maximumStep) || !options.maximumBacktracks ||
332 !(options.hbar > 0) || !std::isfinite(options.hbar) ||
333 !(options.hessianStep > 0) || !std::isfinite(options.hessianStep) ||
334 !(options.linearTolerance > 0) ||
335 !std::isfinite(options.linearTolerance) ||
336 !(options.constraintTolerance > 0) ||
337 !std::isfinite(options.constraintTolerance) ||
338 !std::isfinite(options.energyShift) ||
339 !(options.nativeJacobianProbeContraction >= 0 &&
340 options.nativeJacobianProbeContraction < 1) ||
341 !std::isfinite(options.nativeJacobianProbeContraction) ||
342 options.retainQuadratic || options.harmonicReferenceHessian.size() ||
343 !gauge.target.allFinite() || gauge.normals.size() != m)
344 throw std::invalid_argument(
345 "Reflected primitive path, native forces and matching rigid gauge "
346 "required");
347 const double h = options.duration / (2 * m), spring = 1 / (h * h);
348 M normals(nd, k);
349 V path(nd);
350 for (std::size_t j = 0; j < m; ++j) {
351 if (initial[j].size() != d || !initial[j].allFinite() ||
352 gauge.normals[j].rows() != d || gauge.normals[j].cols() != k ||
353 !gauge.normals[j].allFinite())
354 throw std::invalid_argument(
355 "Finite reflected coordinates and matching gauge blocks "
356 "required");
357 path.segment(j * d, d) = initial[j];
358 // A zero-column matrix stores no data. middleRows at a nonzero row
359 // would offset that null pointer.
360 if (k > 0) normals.middleRows(j * d, d) = gauge.normals[j];
361 }
362 if ((normals.transpose() * normals - M::Identity(k, k)).norm() >
363 1e-10 * std::max<Eigen::Index>(1, k))
364 throw std::invalid_argument(
365 "Orthonormal reflected gauge columns required");
366 path -= normals * (normals.transpose() * path - gauge.target);
367 PotentialPathResult result;
368 struct State {
369 std::vector<PotentialEvaluation> values;
370 V gradient;
371 double force{}, action{}, constraint{};
372 };
373 auto evaluate = [&](const V& q) {
374 State state;
375 std::vector<V> points;
376 for (std::size_t j = 0; j < m; ++j)
377 points.push_back(metric.physical(q.segment(j * d, d)));
378 result.evaluations += m;
379 if (potential.evaluateBatch) {
380 ++result.batchEvaluations;
381 state.values = potential.evaluateBatch(points);
382 } else
383 for (const auto& x: points)
384 state.values.push_back(potential.evaluate(x));
385 if (state.values.size() != m)
386 throw std::runtime_error("Reflected native batch shape differs");
387 state.gradient.resize(nd);
388 for (std::size_t j = 0; j < m; ++j) {
389 auto& value = state.values[j];
390 if (!std::isfinite(value.energy) || value.gradient.size() != d ||
391 !value.gradient.allFinite())
392 throw std::runtime_error("Invalid reflected native return");
393 value.gradient = metric.gradient(value.gradient);
394 V g = value.gradient;
395 if (j)
396 g += spring * (q.segment(j * d, d) - q.segment((j - 1) * d, d));
397 if (j + 1 < m)
398 g += spring * (q.segment(j * d, d) - q.segment((j + 1) * d, d));
399 state.gradient.segment(j * d, d) = g;
400 state.force = std::max(state.force, g.norm());
401 state.action += 2 * h * (value.energy - options.energyShift);
402 if (j)
403 state.action +=
404 (q.segment(j * d, d) - q.segment((j - 1) * d, d))
405 .squaredNorm() /
406 h;
407 }
408 state.constraint = (normals.transpose() * q - gauge.target).norm();
409 return state;
410 };
411 auto hessian = [&](const V& q) {
412 M full = M::Zero(nd + k, nd + k);
413 for (std::size_t j = 0; j < m; ++j) {
414 const V x = metric.physical(q.segment(j * d, d));
415 M physical;
416 if (potential.searchHessian) {
417 physical = potential.searchHessian(x);
418 ++result.searchHessianEvaluations;
419 } else if (potential.hessian) {
420 physical = potential.hessian(x);
421 ++result.hessianEvaluations;
422 } else {
423 physical.resize(d, d);
424 for (Eigen::Index a = 0; a < d; ++a) {
425 V p = x, b = x;
426 p[a] += options.hessianStep;
427 b[a] -= options.hessianStep;
428 auto point = [&](const V& x) {
429 if (potential.evaluate) return potential.evaluate(x);
430 ++result.batchEvaluations;
431 const auto values = potential.evaluateBatch({x});
432 if (values.size() != 1)
433 throw std::runtime_error(
434 "Reflected Hessian batch shape differs");
435 return values.front();
436 };
437 const auto vp = point(p), vb = point(b);
438 result.evaluations += 2;
439 if (vp.gradient.size() != d || vb.gradient.size() != d ||
440 !vp.gradient.allFinite() || !vb.gradient.allFinite())
441 throw std::runtime_error(
442 "Invalid reflected native Hessian gradient");
443 physical.col(a) =
444 (vp.gradient - vb.gradient) / (2 * options.hessianStep);
445 }
446 ++result.hessianEvaluations;
447 }
448 if (physical.rows() != d || physical.cols() != d ||
449 !physical.allFinite())
450 throw std::runtime_error(
451 "Invalid reflected physical curvature");
452 result.maximumHessianAsymmetry =
453 std::max(result.maximumHessianAsymmetry,
454 (physical - physical.transpose()).norm());
455 full.block(j * d, j * d, d, d) =
456 metric.hessian(M(.5 * (physical + physical.transpose()))) +
457 double((j > 0) + (j + 1 < m)) * spring * M::Identity(d, d);
458 if (j) {
459 full.block(j * d, (j - 1) * d, d, d) =
460 -spring * M::Identity(d, d);
461 full.block((j - 1) * d, j * d, d, d) =
462 -spring * M::Identity(d, d);
463 }
464 }
465 full.topRightCorner(nd, k) = normals;
466 full.bottomLeftCorner(k, nd) = normals.transpose();
467 return full;
468 };
469 ReflectedSearchCache localSearch;
470 const bool reusableSearch =
471 bool(potential.searchHessian) && options.nativeJacobianRefinement;
472 if (retainedSearch && !reusableSearch) retainedSearch->invalidate();
473 auto& searchCache =
474 reusableSearch && retainedSearch ? *retainedSearch : localSearch;
475 if (reusableSearch)
476 searchCache.bind(m, metric, normals, gauge.target, options.duration,
477 options.hessianStep, potential,
478 options.linearTolerance);
479 auto state = evaluate(path);
480 for (std::size_t iteration = 0; iteration <= options.maximumIterations;
481 ++iteration) {
482 result.iterations = iteration;
483 PathIteration history;
484 history.iteration = iteration;
485 history.fullForce = state.force;
486 history.action = state.action;
487 history.evaluations = result.evaluations;
488 history.hessianEvaluations = result.hessianEvaluations;
489 result.history.push_back(history);
490 if (state.force <= options.forceTolerance &&
491 state.constraint <= options.constraintTolerance) {
492 result.converged = true;
493 break;
494 }
495 if (iteration == options.maximumIterations) {
496 result.failure = "Reflected native path iteration limit";
497 break;
498 }
499 const bool rebuilt = !reusableSearch || searchCache.needsRefresh();
500 if (rebuilt) {
501 const auto begin = std::chrono::steady_clock::now();
502 M assembled = hessian(path);
503 searchCache.recordAssembly(
504 std::chrono::duration<double>(std::chrono::steady_clock::now() -
505 begin)
506 .count());
507 searchCache.build(std::move(assembled));
508 } else
509 searchCache.reuse();
510 const auto& matrix = searchCache.matrix();
511 V rhs(nd + k);
512 rhs.head(nd) = -state.gradient;
513 rhs.tail(k) = gauge.target - normals.transpose() * path;
514 V step = searchCache.solve(rhs);
515 if (!step.allFinite() ||
516 (matrix * step - rhs).norm() >
517 options.linearTolerance * std::max(1., rhs.norm())) {
518 result.failure =
519 "Reflected Newton solve fails its native residual check";
520 break;
521 }
522 std::optional<std::pair<V, State>> searchProbe;
523 if (reusableSearch && options.nativeJacobianProbeContraction > 0) {
524 double largest = 0;
525 for (std::size_t j = 0; j < m; ++j)
526 largest = std::max(largest, step.segment(j * d, d).norm());
527 const double scale = largest > options.maximumStep
528 ? options.maximumStep / largest
529 : 1.;
530 V candidate = path + scale * step.head(nd);
531 candidate -=
532 normals * (normals.transpose() * candidate - gauge.target);
533 auto next = evaluate(candidate);
534 searchCache.recordProbe();
535 const double target = options.nativeJacobianProbeContraction;
536 const bool decreases =
537 next.gradient.squaredNorm() < state.gradient.squaredNorm();
538 const bool useful =
539 next.gradient.squaredNorm() <=
540 target * target * state.gradient.squaredNorm() ||
541 next.force <= options.forceTolerance;
542 if (decreases && useful &&
543 next.constraint <= options.constraintTolerance) {
544 path = std::move(candidate);
545 state = std::move(next);
546 ++result.acceptedSteps;
547 searchCache.recordProbeAcceptance();
548 continue;
549 }
550 searchProbe.emplace(std::move(candidate), std::move(next));
551 }
552 auto evaluateTrial = [&](const V& candidate) {
553 if (searchProbe &&
554 (candidate.array() == searchProbe->first.array()).all()) {
555 searchCache.recordProbeReuse();
556 return searchProbe->second;
557 }
558 return evaluate(candidate);
559 };
560 if (potential.searchHessian && options.nativeJacobianRefinement) {
561 auto project = [&](const V& v) -> V {
562 return v - normals * (normals.transpose() * v);
563 };
564 auto nativeAction = [&](const V& vector) -> V {
565 const V direction = project(vector);
566 double size = 0;
567 for (std::size_t j = 0; j < m; ++j)
568 size = std::max(size, (direction.segment(j * d, d).array() /
569 metric.roots().array())
570 .abs()
571 .maxCoeff());
572 if (size == 0) return V::Zero(nd);
573 const double delta = options.hessianStep / size;
574 const auto plus = evaluate(path + delta * direction),
575 minus = evaluate(path - delta * direction);
576 V response(nd);
577 for (std::size_t j = 0; j < m; ++j) {
578 V value =
579 (plus.values[j].gradient - minus.values[j].gradient) /
580 (2 * delta);
581 if (j)
582 value += spring * (direction.segment(j * d, d) -
583 direction.segment((j - 1) * d, d));
584 if (j + 1 < m)
585 value += spring * (direction.segment(j * d, d) -
586 direction.segment((j + 1) * d, d));
587 response.segment(j * d, d) = value;
588 }
589 return project(response);
590 };
591 auto precondition = [&](const V& v) -> V {
592 V right = V::Zero(nd + k);
593 right.head(nd) = project(v);
594 const V solved = searchCache.solve(right);
595 return project(V(solved.head(nd)));
596 };
597 const auto refined = refineNativeNewtonStep(
598 nativeAction, precondition, -project(state.gradient),
599 project(V(step.head(nd))));
600 step.head(nd) = refined.step;
601 result.history.back().linearResidual = refined.residualNorm;
602 // Reuse an owned search matrix while its native Krylov response
603 // remains effective. Native Jacobian actions follow every path.
604 searchCache.requestRefresh(!refined.converged ||
605 refined.iterations > 8);
606 }
607 double largest = 0;
608 for (std::size_t j = 0; j < m; ++j)
609 largest = std::max(largest, step.segment(j * d, d).norm());
610 double scale =
611 largest > options.maximumStep ? options.maximumStep / largest : 1.;
612 bool accepted = false;
613 for (std::size_t trial = 0; trial < options.maximumBacktracks;
614 ++trial, scale *= .5) {
615 V candidate = path + scale * step.head(nd);
616 candidate -=
617 normals * (normals.transpose() * candidate - gauge.target);
618 auto next = evaluateTrial(candidate);
619 const bool decreases =
620 potential.searchHessian
621 ? next.gradient.squaredNorm() < state.gradient.squaredNorm()
622 : next.force < state.force;
623 if (decreases && next.constraint <= options.constraintTolerance) {
624 path = std::move(candidate);
625 state = std::move(next);
626 accepted = true;
627 ++result.acceptedSteps;
628 break;
629 }
630 }
631 if (!accepted && potential.searchHessian) {
632 // The native residual merit has feasible gradient P J F. Two
633 // native force batches supply J F without constructing the full
634 // physical Hessian. Search curvature only preconditions descent.
635 double physicalSize = 0;
636 for (std::size_t j = 0; j < m; ++j)
637 physicalSize = std::max(
638 physicalSize, (state.gradient.segment(j * d, d).array() /
639 metric.roots().array())
640 .abs()
641 .maxCoeff());
642 if (physicalSize > 0) {
643 const double delta = options.hessianStep / physicalSize;
644 const auto plus = evaluate(path + delta * state.gradient);
645 const auto minus = evaluate(path - delta * state.gradient);
646 V meritGradient =
647 (plus.gradient - minus.gradient) / (2 * delta);
648 meritGradient -=
649 normals * (normals.transpose() * meritGradient);
650 const auto meritBegin = std::chrono::steady_clock::now();
651 const M jacobian = matrix.topLeftCorner(nd, nd);
652 // Regularization resolves roundoff in the squared search
653 // operator without imposing a force floor on a resolved soft
654 // mode.
655 const double regularizer = std::max(
656 1e-15, std::sqrt(std::numeric_limits<double>::epsilon()) *
657 jacobian.norm() / std::sqrt(double(nd)));
658 M positive = M::Zero(nd + k, nd + k);
659 positive.topLeftCorner(nd, nd) =
660 jacobian.transpose() * jacobian;
661 positive.topLeftCorner(nd, nd).diagonal().array() +=
662 regularizer * regularizer;
663 positive.topRightCorner(nd, k) = normals;
664 positive.bottomLeftCorner(k, nd) = normals.transpose();
665 V descentRhs = V::Zero(nd + k);
666 descentRhs.head(nd) = -meritGradient;
667 V descent = positive.partialPivLu().solve(descentRhs).head(nd);
668 searchCache.recordMeritAlgebra(
669 std::chrono::duration<double>(
670 std::chrono::steady_clock::now() - meritBegin)
671 .count());
672 descent -= normals * (normals.transpose() * descent);
673 double slope = meritGradient.dot(descent);
674 if (!descent.allFinite() || !(slope < 0)) {
675 descent = -meritGradient;
676 slope = -meritGradient.squaredNorm();
677 }
678 largest = 0;
679 for (std::size_t j = 0; j < m; ++j)
680 largest =
681 std::max(largest, descent.segment(j * d, d).norm());
682 scale = largest > options.maximumStep
683 ? options.maximumStep / largest
684 : 1.;
685 for (std::size_t trial = 0;
686 slope < 0 && trial < options.maximumBacktracks;
687 ++trial, scale *= .5) {
688 V candidate = path + scale * descent;
689 candidate -= normals * (normals.transpose() * candidate -
690 gauge.target);
691 auto next = evaluateTrial(candidate);
692 if (.5 * next.gradient.squaredNorm() <=
693 .5 * state.gradient.squaredNorm() +
694 1e-4 * scale * slope &&
695 next.constraint <= options.constraintTolerance) {
696 path = std::move(candidate);
697 state = std::move(next);
698 accepted = true;
699 ++result.acceptedSteps;
700 break;
701 }
702 }
703 }
704 }
705 if (!accepted && potential.searchHessian &&
706 options.nativeJacobianRefinement && !rebuilt) {
707 state = evaluate(path);
708 searchCache.requestRefresh();
709 continue;
710 }
711 if (!accepted) {
712 result.failure = "Reflected native path force does not decrease";
713 break;
714 }
715 }
716 result.action = state.action;
717 result.actionOverHbar = state.action / options.hbar;
718 result.fullForce = state.force;
719 result.constraintResidual = state.constraint;
720 result.fullStationarityQualified = result.converged;
721 result.conditionalStationarityQualified = result.converged;
722 result.conditionalForce = state.force;
723 result.normalForces = normals.transpose() * state.gradient;
724 for (std::size_t j = 0; j < 2 * m; ++j) {
725 const auto index = j < m ? j : 2 * m - 1 - j;
726 result.path.push_back(path.segment(index * d, d));
727 result.physicalPath.push_back(metric.physical(result.path.back()));
728 result.energies.push_back(state.values[index].energy);
729 result.fullGradient.push_back(state.gradient.segment(index * d, d));
730 }
731 result.conditionalGradient = result.fullGradient;
732 return result;
733}
734} // namespace gpr::quantum
@ x
Definition Enums.h:28
const Eigen::VectorXd & roots() const noexcept
Eigen::VectorXd gradient(const Eigen::VectorXd &physicalGradient) const
Eigen::VectorXd physical(const Eigen::VectorXd &q) const
Eigen::MatrixXd hessian(const Eigen::MatrixXd &physicalHessian) const
Eigen::Index dimension() const noexcept
const Eigen::VectorXd & origin() const noexcept
double searchResidualCheckSeconds() const noexcept
std::size_t reuses() const noexcept
std::size_t reusedProbes() const noexcept
std::size_t meritSolves() const noexcept
void recordMeritAlgebra(double seconds) noexcept
std::size_t acceptedProbes() const noexcept
std::size_t solves() const noexcept
std::size_t probes() const noexcept
const Eigen::PartialPivLU< M > & factor() const
std::size_t factorizations() const noexcept
std::size_t sparseFactorizations() const noexcept
const std::string & sparseFallbackReason() const noexcept
std::size_t sparseDenseFallbacks() const noexcept
void requestRefresh(bool value=true) noexcept
void bind(std::size_t nodes, const MassMetric &metric, const M &normals, const V &target, double duration, double differenceStep, const PathPotential &owner, double linearTolerance=1e-8)
std::size_t searchResidualChecks() const noexcept
void recordAssembly(double seconds) noexcept
Half refined(GaussianProcessRegression &gp, const GradientOracle &oracle, const Eigen::VectorXd &x, Kind kind, const Options &raw_options)
Models for quantum-path (instanton) searches: arc and tail actions, amplitude continuation.
PotentialPathResult optimizeReflectedPotentialPath(const std::vector< Eigen::VectorXd > &initial, const MassMetric &metric, const PathPotential &potential, const PathConstraints &gauge, const PotentialPathOptions &options={}, ReflectedSearchCache *retainedSearch=nullptr)
PotentialPathResult assessReflectedPotentialPath(const std::vector< Eigen::VectorXd > &halfMassPath, const MassMetric &metric, const std::vector< PotentialEvaluation > &physicalValues, const PathConstraints &gauge, const PotentialPathOptions &options={})
NativeNewtonKrylovResult refineNativeNewtonStep(const std::function< Eigen::VectorXd(const Eigen::VectorXd &)> &jacobian, const std::function< Eigen::VectorXd(const Eigen::VectorXd &)> &preconditioner, const Eigen::VectorXd &rhs, const Eigen::VectorXd &initial, double relativeTolerance=.1, std::size_t maximumIterations=24)
VecchiaResult evaluate(const Eigen::MatrixXd &points, const Eigen::VectorXd &y, double lengthscale, double noise, int max_neighbours)
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