218 const std::vector<Eigen::VectorXd>& halfMassPath,
const MassMetric& metric,
219 const std::vector<PotentialEvaluation>& physicalValues,
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,
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() ||
243 throw std::invalid_argument(
244 "Reflected primitive path, supplied physical values and matching "
245 "rigid gauge required");
248 for (std::size_t j = 0; j < m; ++j) {
249 if (halfMassPath[j].size() != d || !halfMassPath[j].allFinite() ||
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];
261 if (k > 0) normals.middleRows(j * d, d) = gauge.
normals[j];
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);
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());
277 2 * h * (physicalValues[j].energy - options.energyShift);
280 (halfMassPath[j] - halfMassPath[j - 1]).squaredNorm() / h;
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)
299 "Supplied reflected path does not satisfy force and gauge "
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));
308 result.conditionalGradient = result.fullGradient;
317 const std::vector<Eigen::VectorXd>& initial,
const MassMetric& metric,
320 ReflectedSearchCache* retainedSearch =
nullptr)
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,
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() ||
344 throw std::invalid_argument(
345 "Reflected primitive path, native forces and matching rigid gauge "
347 const double h = options.duration / (2 * m), spring = 1 / (h * h);
350 for (std::size_t j = 0; j < m; ++j) {
351 if (initial[j].size() != d || !initial[j].allFinite() ||
354 throw std::invalid_argument(
355 "Finite reflected coordinates and matching gauge blocks "
357 path.segment(j * d, d) = initial[j];
360 if (k > 0) normals.middleRows(j * d, d) = gauge.
normals[j];
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;
369 std::vector<PotentialEvaluation> values;
371 double force{}, action{}, constraint{};
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;
380 ++result.batchEvaluations;
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;
396 g += spring * (q.segment(j * d, d) - q.segment((j - 1) * d, d));
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);
404 (q.segment(j * d, d) - q.segment((j - 1) * d, d))
408 state.constraint = (normals.transpose() * q - gauge.
target).norm();
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));
418 ++result.searchHessianEvaluations;
419 }
else if (potential.
hessian) {
421 ++result.hessianEvaluations;
423 physical.resize(d, d);
424 for (Eigen::Index a = 0; a < d; ++a) {
426 p[a] += options.hessianStep;
427 b[a] -= options.hessianStep;
428 auto point = [&](
const V&
x) {
430 ++result.batchEvaluations;
432 if (values.size() != 1)
433 throw std::runtime_error(
434 "Reflected Hessian batch shape differs");
435 return values.front();
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");
444 (vp.gradient - vb.gradient) / (2 * options.hessianStep);
446 ++result.hessianEvaluations;
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);
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);
465 full.topRightCorner(nd, k) = normals;
466 full.bottomLeftCorner(k, nd) = normals.transpose();
470 const bool reusableSearch =
471 bool(potential.
searchHessian) && options.nativeJacobianRefinement;
472 if (retainedSearch && !reusableSearch) retainedSearch->
invalidate();
474 reusableSearch && retainedSearch ? *retainedSearch : localSearch;
476 searchCache.bind(m, metric, normals, gauge.
target, options.duration,
477 options.hessianStep, potential,
478 options.linearTolerance);
480 for (std::size_t iteration = 0; iteration <= options.maximumIterations;
482 result.iterations = 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;
495 if (iteration == options.maximumIterations) {
496 result.failure =
"Reflected native path iteration limit";
499 const bool rebuilt = !reusableSearch || searchCache.needsRefresh();
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() -
507 searchCache.build(std::move(assembled));
510 const auto& matrix = searchCache.matrix();
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())) {
519 "Reflected Newton solve fails its native residual check";
522 std::optional<std::pair<V, State>> searchProbe;
523 if (reusableSearch && options.nativeJacobianProbeContraction > 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
530 V candidate = path + scale * step.head(nd);
532 normals * (normals.transpose() * candidate - gauge.
target);
534 searchCache.recordProbe();
535 const double target = options.nativeJacobianProbeContraction;
536 const bool decreases =
537 next.gradient.squaredNorm() < state.gradient.squaredNorm();
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();
550 searchProbe.emplace(std::move(candidate), std::move(next));
552 auto evaluateTrial = [&](
const V& candidate) {
554 (candidate.array() == searchProbe->first.array()).all()) {
555 searchCache.recordProbeReuse();
556 return searchProbe->second;
560 if (potential.
searchHessian && options.nativeJacobianRefinement) {
561 auto project = [&](
const V& v) -> V {
562 return v - normals * (normals.transpose() * v);
564 auto nativeAction = [&](
const V& vector) -> V {
565 const V direction = project(vector);
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())
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);
577 for (std::size_t j = 0; j < m; ++j) {
579 (plus.values[j].gradient - minus.values[j].gradient) /
582 value += spring * (direction.segment(j * d, d) -
583 direction.segment((j - 1) * d, d));
585 value += spring * (direction.segment(j * d, d) -
586 direction.segment((j + 1) * d, d));
587 response.segment(j * d, d) = value;
589 return project(response);
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)));
598 nativeAction, precondition, -project(state.gradient),
599 project(V(step.head(nd))));
601 result.history.back().linearResidual =
refined.residualNorm;
608 for (std::size_t j = 0; j < m; ++j)
609 largest = std::max(largest, step.segment(j * d, d).norm());
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);
617 normals * (normals.transpose() * candidate - gauge.
target);
618 auto next = evaluateTrial(candidate);
619 const bool decreases =
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);
627 ++result.acceptedSteps;
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())
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);
647 (plus.gradient - minus.gradient) / (2 * delta);
649 normals * (normals.transpose() * meritGradient);
650 const auto meritBegin = std::chrono::steady_clock::now();
651 const M jacobian = matrix.topLeftCorner(nd, nd);
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)
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();
679 for (std::size_t j = 0; j < m; ++j)
681 std::max(largest, descent.segment(j * d, d).norm());
682 scale = largest > options.maximumStep
683 ? options.maximumStep / largest
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 -
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);
699 ++result.acceptedSteps;
706 options.nativeJacobianRefinement && !rebuilt) {
708 searchCache.requestRefresh();
712 result.failure =
"Reflected native path force does not decrease";
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));
731 result.conditionalGradient = result.fullGradient;