Loading...
Searching...
No Matches
gpr::quantum Namespace Reference

Models for quantum-path (instanton) searches: arc and tail actions, amplitude continuation. More...

Namespaces

namespace  bathresponse
namespace  beadcorrection
namespace  elementfluct
namespace  functionaldesign
namespace  gaussian
namespace  ratepost
namespace  ringbath
namespace  ringspread
namespace  spectraldet

Classes

class  AffineGaussianArcModel
struct  AffineGaussianArcOptions
class  AffineGaussianJet
struct  AffinePathBoundary
struct  AmplitudeContinuationOptions
struct  AmplitudeContinuationResult
struct  AmplitudeSample
class  ArcTailAction
struct  ArcTailEvaluation
struct  ArcTailForceGradientData
struct  ArcTailNewtonStep
struct  ArcTailPotential
struct  ArcTailSearchOptions
struct  ArcTailSearchResult
class  CartesianNaturalCubicPath
struct  CentralHessianColumnBatch
struct  ConstrainedFamilyPoint
struct  ConstrainedImaginaryTimeSample
struct  ConstrainedImaginaryTimeTrajectory
struct  ConstrainedQuantumBandBranch
struct  CyclicQuarticReduction
struct  CyclicSoftMode
struct  GaussianLaw
struct  GaussianMoment
struct  GaussianPolynomialMoments
struct  GPArcTailOptions
struct  GPArcTailResult
struct  GPBandNodeScore
struct  GPLineIntegralNEBOptions
struct  GPLineIntegralNEBResult
struct  HarmonicLinkEvaluation
class  HarmonicPathCorrection
struct  HarmonicPointCurvature
struct  HarmonicPointInertia
class  HarmonicReference
struct  HarmonicTail
class  HarmonicTurningTail
struct  IndexTargetedArcKernel
struct  IsoenergyTurningPointRefinement
struct  JacobiPathEvaluation
struct  JacobiSegment
struct  JacobiTurningPoint
struct  LineIntegralFeasibilityResult
struct  LineIntegralFIREState
class  LineIntegralGPModel
struct  LineIntegralNEBOptions
struct  LineIntegralNEBResult
struct  LineIntegralNEBState
struct  LineIntegralOrbit
class  MassMetric
struct  MolecularBlockFluctuations
struct  MolecularRingFluctuations
class  NativeGPPath
struct  NativeNewtonKrylovResult
struct  PathConstraints
struct  PathIteration
struct  PathPotential
struct  PolynomialTerm
class  PositiveArcAction
struct  PotentialEvaluation
struct  PotentialPathOptions
struct  PotentialPathResult
class  QuadraticMeanGPModel
struct  ReducedGaussianGLEResult
struct  ReducedGaussianSegmentResult
struct  ReferenceForceGradientValue
class  ReflectedSearchCache
struct  SaddleFamilyPoint
class  SearchKktFactor
struct  SphereEnergyProjection
struct  SurrogatePathTrustDecision
class  ThermalGeodesicSeed
struct  ThermalJacobiPeriod
struct  TwistedConstraintStep
class  WellJetCorrection
struct  ZeroEnergyGeodesicEvaluation
struct  ZeroEnergyGeodesicOptions
struct  ZeroEnergyGeodesicPotential
struct  ZeroEnergyGeodesicResult

Typedefs

using SparsePolynomial = std::vector<PolynomialTerm>
using LineIntegralNEBBatch
using Vector = Eigen::VectorXd
using Matrix = Eigen::MatrixXd
using SearchSparseMatrix = Eigen::SparseMatrix<double, Eigen::ColMajor, int>

Enumerations

enum class  LineIntegralProposalAcceptance { ForceDescent , AdmissibleBand }
enum class  LineIntegralAction { MomentumTrapezoid , LinearPotential }
enum class  ReferenceDiscretization { SymmetricResidual , FrequencyFittedKinetic }

Functions

AmplitudeContinuationResult continuePotentialPathAmplitude (const std::vector< Eigen::VectorXd > &initial, const MassMetric &metric, const PathPotential &potential, const AffinePathBoundary &boundary, const PathConstraints &constraints, const AmplitudeContinuationOptions &options)
AmplitudeContinuationResult continuePotentialPathAmplitudeInPhasePlane (const std::vector< Eigen::VectorXd > &initial, const MassMetric &metric, const PathPotential &potential, const AffinePathBoundary &boundary, const PathConstraints &constraints, Eigen::Index phaseColumn, const AmplitudeContinuationOptions &options)
template<class Action>
ArcTailForceGradientData prepareArcTailForceGradient (const Action &action, const std::vector< Eigen::VectorXd > &points, double duration, const std::vector< PotentialEvaluation > &native, const ArcTailPotential &potential, const ArcTailSearchOptions &options, const std::function< std::vector< PotentialEvaluation >(const std::vector< Eigen::VectorXd > &)> &ownedEvaluate)
template<class Action>
ArcTailEvaluation evaluateArcTailForceGradient (const Action &action, const std::vector< Eigen::VectorXd > &points, const std::vector< PotentialEvaluation > &native, double duration, const ArcTailForceGradientData &data, const std::vector< Eigen::MatrixXd > &searchHessians={}, const std::vector< Eigen::MatrixXd > &searchThirdContractions={})
ArcTailNewtonStep solveArcTailNewton (const ArcTailEvaluation &state, const std::vector< M > &normals, const V &correction)
ArcTailNewtonStep solveArcTailNewton (const ArcTailEvaluation &evaluation, const std::vector< Eigen::MatrixXd > &orthonormalNormals, const Eigen::VectorXd &constraintCorrection)
ArcTailSearchResult optimizeArcTail (const ArcTailAction &action, const std::vector< V > &initial, double duration, const PathConstraints &constraints, const ArcTailPotential &potential, const ArcTailSearchOptions &options, const std::function< void(const ArcTailSearchResult &)> &retain)
ArcTailSearchResult optimizeArcTail (const ArcTailAction &action, const std::vector< Eigen::VectorXd > &initial, double initialArcDuration, const PathConstraints &constraints, const ArcTailPotential &potential, const ArcTailSearchOptions &options={}, const std::function< void(const ArcTailSearchResult &)> &retain={})
Eigen::MatrixXd boundedStationaryBathReference (const Eigen::MatrixXd &hessian, const Eigen::MatrixXd &directions)
void evaluateCentralHessianColumns (const std::vector< Eigen::VectorXd > &centers, const std::vector< Eigen::Index > &columns, double step, const PathPotential &potential, const std::function< void(const CentralHessianColumnBatch &)> &retain)
double logConstraintFamilyJacobian (const Eigen::MatrixXd &normals, const std::vector< Eigen::MatrixXd > &derivatives, const Eigen::MatrixXd &targets, const Eigen::VectorXd &point)
double logImFConstrainedFamilyRate (double referenceAction, const gaussian::TwistedTraceResult &reference, const std::vector< ConstrainedFamilyPoint > &family, Eigen::Index k, double hbar, double symmetryFactor)
template<class NativeEvaluate, class NativeEnergy>
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)
template<class NativeEvaluate, class NativeEnergy>
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)
std::vector< Eigen::VectorXd > sampleBondCenteredImaginaryTimeRing (const ConstrainedImaginaryTimeTrajectory &trajectory, std::size_t fullBeads)
double affineQuantumBandLogCoarea (const Eigen::MatrixXd &constraintGradients)
ConstrainedQuantumBandBranch constrainedQuantumBandBranch (double action, const gaussian::TwistedRestrictedResult &fluctuations, Eigen::Index physicalCodimension, Eigen::Index integratedChartDimensions, double quadratureWeight, double logCoareaJacobian)
ConstrainedQuantumBandBranch affineConstrainedQuantumBandBranch (double action, const gaussian::TwistedRestrictedResult &fluctuations, const Eigen::MatrixXd &constraintGradients, double quadratureWeight=1.)
ConstrainedQuantumBandBranch affineConstrainedQuantumBandBranch (double action, const gaussian::TwistedRestrictedResult &fluctuations, const Eigen::VectorXd &constraintGradient, double quadratureWeight=1.)
double logConstrainedQuantumBandWeight (const std::vector< ConstrainedQuantumBandBranch > &branches, double beta, double hbar)
double constrainedQuantumBandFreeEnergyDifference (double logWeight, double referenceLogWeight, double beta)
CyclicSoftMode cyclicSoftMode (const gaussian::Segment &link, std::size_t nodes)
CyclicQuarticReduction cyclicQuarticReduction (const gaussian::Segment &link, std::size_t nodes, const V &cubic, double fourth)
std::vector< V > cyclicQuarticSeed (const CyclicQuarticReduction &reduction, double phase)
CyclicQuarticReduction cyclicQuarticReduction (const gaussian::Segment &link, std::size_t nodes, const Eigen::VectorXd &cubicVV, double quarticVVVV)
ArcTailNewtonStep solveFixedTimeArcNewton (const ArcTailEvaluation &state, const std::vector< Eigen::MatrixXd > &normals, const Eigen::VectorXd &correction)
ArcTailSearchOptions fixedTimeArcOptions ()
template<class Action>
ArcTailSearchResult optimizeFixedTimeArc (const Action &action, const std::vector< Eigen::VectorXd > &initial, double duration, const PathConstraints &constraints, const ArcTailPotential &potential, const ArcTailSearchOptions &options=fixedTimeArcOptions(), const std::function< void(const ArcTailSearchResult &)> &retain={}, double maximumDisplacement=std::numeric_limits< double >::infinity())
gaussian::Segment frequencyFittedKinetic (const Eigen::MatrixXd &curvature, double h)
long double weightedEventBound (const GaussianPolynomialMoments &moments, long double probabilityBound)
GaussianPolynomialMoments evaluateGaussianPolynomial (const GaussianLaw &law, const SparsePolynomial &polynomial, std::optional< long double > eventProbabilityBound)
Eigen::VectorXd geodesicMeshConstraints (const std::vector< Eigen::VectorXd > &path, const std::vector< double > &weights={})
std::vector< Eigen::VectorXd > retractGeodesicMesh (const std::vector< Eigen::VectorXd > &path, const std::vector< double > &weights, double tolerance, const Eigen::VectorXd &target={})
ZeroEnergyGeodesicPotential restrictGeodesicProposal (ZeroEnergyGeodesicPotential model, std::vector< Eigen::VectorXd > center, double radius)
template<class Model, class Action>
GPArcTailResult optimizeGPArcTail (const Action &action, const std::vector< Eigen::VectorXd > &initial, double duration, const PathConstraints &constraints, const ArcTailPotential &potential, Model &model, const GPArcTailOptions &options={}, const std::function< void(const GPArcTailResult &)> &retain={})
bool sameGPBandPoint (const Eigen::VectorXd &left, const Eigen::VectorXd &right)
std::vector< GPBandNodeScore > selectGPBandNodes (const std::vector< Eigen::VectorXd > &points, const std::vector< double > &massGradientVariance, const Eigen::VectorXd &weights, const std::vector< Eigen::VectorXd > &measured, std::size_t maximumNodes)
std::vector< Eigen::VectorXd > lineIntegralSIDPPSeed (neb::NEBPath &physicalBand, int atoms, const std::vector< char > &moving, const MassMetric &metric, double alpha=.33)
template<class Model>
GPLineIntegralNEBResult optimizeGPLineIntegralNEB (const std::vector< Eigen::VectorXd > &initial, const LineIntegralNEBBatch &potential, Model &model, const GPLineIntegralNEBOptions &options={}, const std::function< void(const GPLineIntegralNEBResult &)> &retain={})
Eigen::MatrixXd stationaryBathReference (const Eigen::MatrixXd &hessian, const Eigen::MatrixXd &directions)
IndexTargetedArcKernel indexOneArcKernel (const std::vector< gaussian::Segment > &segments, const Eigen::MatrixXd &normal)
double quadraticArcActionChange (const ArcTailEvaluation &state, const std::vector< Eigen::VectorXd > &displacement)
bool arcActionChangeAgrees (double actual, double predicted, double scale)
JacobiSegment jacobiSegment (const Eigen::VectorXd &left, const Eigen::VectorXd &right, const PotentialEvaluation &vl, const PotentialEvaluation &vr, double energy)
JacobiPathEvaluation evaluateJacobiPath (const std::vector< Eigen::VectorXd > &points, const std::vector< PotentialEvaluation > &native, double energy)
JacobiTurningPoint findJacobiTurningPoint (const Eigen::VectorXd &left, const Eigen::VectorXd &right, double energy, const std::function< PotentialEvaluation(const Eigen::VectorXd &)> &evaluate, double energyTolerance=1e-9, std::size_t maximumEvaluations=64)
LineIntegralNEBState evaluateLineIntegralNEB (const std::vector< Eigen::VectorXd > &q, const std::vector< PotentialEvaluation > &values, double energy, double spring=1., double contour=10., double hbar=1., LineIntegralAction action=LineIntegralAction::MomentumTrapezoid, bool jctcCompatible=false, double contourRight=0., double actionForceCutoff=1e-4)
std::vector< Eigen::VectorXd > lineIntegralSearchForces (const std::vector< Eigen::VectorXd > &q, const std::vector< PotentialEvaluation > &values, const LineIntegralNEBState &state, const LineIntegralNEBOptions &options)
LineIntegralFeasibilityResult restoreLineIntegralInterior (std::vector< Eigen::VectorXd > &trial, std::vector< PotentialEvaluation > &values, const std::vector< PotentialEvaluation > &source, const LineIntegralNEBOptions &options, const LineIntegralNEBBatch &native, std::size_t maximumCorrections=4)
LineIntegralNEBResult optimizeLineIntegralNEB (const std::vector< Eigen::VectorXd > &initial, const LineIntegralNEBBatch &potential, const LineIntegralNEBOptions &options={}, const std::function< void(const LineIntegralNEBResult &)> &retain={}, LineIntegralFIREState *fireState=nullptr, const std::function< bool(const std::vector< Eigen::VectorXd > &)> &earlyStop={})
LineIntegralOrbit lineIntegralOrbit (const LineIntegralNEBResult &result, double energy, std::size_t beads, double hbar=1., double boltzmann=1., double tolerance=1e-8)
std::vector< Eigen::VectorXd > reparameterizeLineIntegralString (const std::vector< Eigen::VectorXd > &path)
std::vector< Eigen::VectorXd > lineIntegralStringActionForces (const std::vector< Eigen::VectorXd > &q, const std::vector< PotentialEvaluation > &values, double energy, double hbar, LineIntegralAction action)
LineIntegralNEBState evaluateLineIntegralString (const std::vector< Eigen::VectorXd > &q, const std::vector< PotentialEvaluation > &values, double energy, double spring=1., double contour=10., double hbar=1., LineIntegralAction action=LineIntegralAction::MomentumTrapezoid)
bool lineIntegralStringNeedsReparameterization (const std::vector< Eigen::VectorXd > &path)
LineIntegralNEBResult optimizeLineIntegralString (const std::vector< Eigen::VectorXd > &initial, const LineIntegralNEBBatch &potential, const LineIntegralNEBOptions &options={}, const std::function< void(const LineIntegralNEBResult &)> &retain={}, LineIntegralFIREState *fireState=nullptr)
MolecularBlockFluctuations molecularBlockFluctuations (const std::vector< Eigen::VectorXd > &positions, const Eigen::VectorXd &masses, const std::vector< Eigen::MatrixXd > &physicalHessians, double beta, double hbar=1)
double molecularBlockLogTunnelingFactor (const MolecularBlockFluctuations &ring, const Eigen::VectorXd &saddleCurvatures, double saddleLogInertia, double actionRelativeToSaddleOverHbar, double beta, double hbar=1)
double molecularBlockLogUnimolecularRate (const MolecularBlockFluctuations &ring, const Eigen::VectorXd &reactantCurvatures, double reactantLogInertia, double actionRelativeToReactantOverHbar, std::size_t nodes, double beta, double hbar=1, double symmetryFactor=1)
Matrix molecularRigidModes (const Vector &x, const Vector &masses)
Matrix molecularInternalBasis (const Vector &x, const Vector &masses)
double molecularLogInertiaDeterminant (const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double copies=1)
MolecularRingFluctuations molecularRingFluctuations (const std::vector< Eigen::VectorXd > &positions, const Eigen::VectorXd &masses, const std::vector< Eigen::MatrixXd > &physicalHessians, double beta, double hbar=1)
double molecularLogTstVibrationalPartition (const Eigen::VectorXd &eigenvalues, double beta, double hbar=1)
double molecularLogHarmonicRingPartition (const Eigen::VectorXd &curvatures, std::size_t nodes, double beta, double hbar=1)
double molecularLogUnimolecularRate (const MolecularRingFluctuations &ring, const Eigen::VectorXd &reactantInternalCurvatures, double reactantLogInertiaDeterminant, double actionRelativeToReactantOverHbar, std::size_t nodes, double beta, double hbar=1, double symmetryFactor=1)
double molecularLogTunnelingFactor (const MolecularRingFluctuations &ring, const Eigen::VectorXd &saddleInternalEigenvalues, double saddleLogInertiaDeterminant, double actionRelativeToSaddleOverHbar, double beta, double hbar=1)
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)
AffinePathBoundary physicalPathBoundary (const MassMetric &m, const Matrix &linear, const Vector &translation)
PotentialPathResult optimizePotentialPath (const Nodes &initial, const MassMetric &metric, const PathPotential &potential, const AffinePathBoundary &boundary, const PathConstraints &constraints, const PotentialPathOptions &options)
PotentialPathResult optimizePotentialPath (const std::vector< Eigen::VectorXd > &initial, const MassMetric &metric, const PathPotential &potential, const AffinePathBoundary &boundary, const PathConstraints &constraints, const PotentialPathOptions &options={})
ReducedGaussianSegmentResult reduceGaussianSegmentsGLE (const std::vector< gaussian::Segment > &segments, const Eigen::MatrixXd &activeBasis, double unresolvedTolerance=1e-12)
gaussian::TwistedTraceResult reducedGaussianSegmentGLETrace (const ReducedGaussianSegmentResult &reduced)
gaussian::TwistedRestrictedResult reducedGaussianSegmentGLERestrictedTrace (const ReducedGaussianSegmentResult &reduced, const Eigen::VectorXd &phaseNormal, double unresolvedTolerance=1e-12)
ReducedGaussianGLEResult reducePeriodicGaussianGLE (const std::vector< Eigen::MatrixXd > &activeHessians, const Eigen::MatrixXd &coupling, const Eigen::MatrixXd &bathCurvature, double step, double unresolvedTolerance=1e-12)
ReducedGaussianGLEResult reducePeriodicGaussianGLE (const std::vector< Eigen::MatrixXd > &activeHessians, const Eigen::MatrixXd &coupling, const Eigen::MatrixXd &bathCurvature, const Eigen::MatrixXd &activeKineticLink, const Eigen::MatrixXd &activeBathKineticLink, const Eigen::MatrixXd &bathKineticLink, double step, double unresolvedTolerance=1e-12)
gaussian::TwistedTraceResult reducedGaussianGLETrace (const ReducedGaussianGLEResult &reduced, double duration, double unresolvedTolerance=1e-12)
gaussian::TwistedRestrictedResult reducedGaussianGLERestrictedTrace (const ReducedGaussianGLEResult &reduced, const Eigen::VectorXd &phaseNormal, double duration, double unresolvedTolerance=1e-12)
ReferenceForceGradientValue referenceForceGradient (const Eigen::VectorXd &residualGradient, const std::function< Eigen::VectorXd(const Eigen::VectorXd &)> &residualHessianAction, double step)
gpr::quantum::gaussian::Segment referenceForceGradientQuadratic (const Eigen::MatrixXd &nativeCurvature, const Eigen::MatrixXd &referenceCurvature, double step, bool corrected=true)
PotentialPathResult assessReflectedPotentialPath (const std::vector< Eigen::VectorXd > &halfMassPath, const MassMetric &metric, const std::vector< PotentialEvaluation > &physicalValues, const PathConstraints &gauge, const PotentialPathOptions &options={})
PotentialPathResult optimizeReflectedPotentialPath (const std::vector< Eigen::VectorXd > &initial, const MassMetric &metric, const PathPotential &potential, const PathConstraints &gauge, const PotentialPathOptions &options={}, ReflectedSearchCache *retainedSearch=nullptr)
template<class Constraints>
void validateReflectionEvenBand (const std::vector< Eigen::VectorXd > &path, const std::vector< double > &weights, const Constraints &constraints, double tolerance)
double reflectOutgoingBand (std::vector< Eigen::VectorXd > &path)
double projectReflectionEvenBand (std::vector< Eigen::VectorXd > &path)
double phasePlaneJacobian (const Eigen::VectorXd &normal, const Eigen::VectorXd &derivative, double targetDerivative, const Eigen::VectorXd &point)
double logImFSaddleFamilyRate (double referenceAction, const gaussian::TwistedTraceResult &reference, const std::vector< SaddleFamilyPoint > &family, double hbar, double symmetryFactor)
template<class Evaluate>
SphereEnergyProjection projectSphereEnergy (const Eigen::VectorXd &center, const Eigen::VectorXd &point, const PotentialEvaluation &value, double energy, double tolerance, const Evaluate &evaluate, std::size_t maximumIterations=8, std::size_t maximumBacktracks=12)
double surrogatePathResidualMerit (const PotentialPathResult &result)
SurrogatePathTrustDecision assessSurrogatePathTrust (double nativeCurrentMerit, double nativeTrialMerit, double modelCurrentMerit, double modelTrialMerit, double radius, double maximumRadius, bool boundary, bool feasible)
SurrogatePathTrustDecision assessSurrogatePathTrust (const PotentialPathResult &nativeCurrent, const PotentialPathResult &nativeTrial, const PotentialPathResult &modelCurrent, const PotentialPathResult &modelTrial, double radius, double maximumRadius, bool boundary, bool feasible)
JacobiPathEvaluation jacobiArcToTurningContour (const std::vector< Eigen::VectorXd > &path, const std::vector< PotentialEvaluation > &native, double energy, Eigen::VectorXd *turningPoint=nullptr)
ThermalJacobiPeriod matchThermalJacobiPeriod (const Eigen::MatrixXd &well, const std::vector< Eigen::VectorXd > &path, const std::vector< PotentialEvaluation > &native, double thermalPeriod, double hbar)
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)
TwistedConstraintStep solveTwistedConstraints (const std::vector< Eigen::MatrixXd > &diagonal, const std::vector< Eigen::VectorXd > &gradient, const std::vector< Eigen::MatrixXd > &normals, const Eigen::MatrixXd &coupling, const Eigen::MatrixXd &twist, const Eigen::VectorXd &correction)
ZeroEnergyGeodesicEvaluation evaluateZeroEnergyGeodesic (const M &omega, double radius, const std::vector< V > &path, const std::vector< PotentialEvaluation > &native, double stiffness, const std::vector< M > &hessians)
ZeroEnergyGeodesicEvaluation evaluateZeroEnergyGeodesic (const M &omega, double radius, const std::vector< V > &path, const std::vector< PotentialEvaluation > &native, double stiffness, const std::vector< M > &hessians, const std::vector< double > &meshWeights)
std::vector< V > solveZeroEnergyGeodesicStep (const ZeroEnergyGeodesicEvaluation &state)
ZeroEnergyGeodesicResult optimizeZeroEnergyGeodesic (const M &omega, double radius, const std::vector< V > &initial, const ZeroEnergyGeodesicPotential &potential, const ZeroEnergyGeodesicOptions &options, const std::function< void(const ZeroEnergyGeodesicResult &)> &retain)
std::vector< Eigen::VectorXd > regridGeodesicPath (const std::vector< Eigen::VectorXd > &path, const std::vector< double > &weights={})
ZeroEnergyGeodesicEvaluation evaluateZeroEnergyGeodesic (const Eigen::MatrixXd &positiveWellRoot, double radius, const std::vector< Eigen::VectorXd > &path, const std::vector< PotentialEvaluation > &native, double meshStiffness=1., const std::vector< Eigen::MatrixXd > &searchHessians={})
ZeroEnergyGeodesicEvaluation evaluateZeroEnergyGeodesic (const Eigen::MatrixXd &positiveWellRoot, double radius, const std::vector< Eigen::VectorXd > &path, const std::vector< PotentialEvaluation > &native, double meshStiffness, const std::vector< Eigen::MatrixXd > &searchHessians, const std::vector< double > &meshWeights)
ZeroEnergyGeodesicResult optimizeZeroEnergyGeodesic (const Eigen::MatrixXd &positiveWellRoot, double radius, const std::vector< Eigen::VectorXd > &initial, const ZeroEnergyGeodesicPotential &potential, const ZeroEnergyGeodesicOptions &options={}, const std::function< void(const ZeroEnergyGeodesicResult &)> &retain={})

Detailed Description

Models for quantum-path (instanton) searches: arc and tail actions, amplitude continuation.

Warning
Experimental instanton and quantum-path work in progress. These interfaces may change.

Typedef Documentation

◆ LineIntegralNEBBatch

Initial value:
std::function<std::vector<PotentialEvaluation>(
const std::vector<Eigen::VectorXd>&)>

Definition at line 379 of file LineIntegralNEB.h.

◆ Matrix

using gpr::quantum::Matrix = Eigen::MatrixXd

Definition at line 15 of file MolecularGeometry.h.

◆ SearchSparseMatrix

using gpr::quantum::SearchSparseMatrix = Eigen::SparseMatrix<double, Eigen::ColMajor, int>

Definition at line 20 of file SearchKktFactor.h.

◆ SparsePolynomial

Definition at line 22 of file GaussianPolynomial.h.

◆ Vector

using gpr::quantum::Vector = Eigen::VectorXd

Definition at line 14 of file MolecularGeometry.h.

Enumeration Type Documentation

◆ LineIntegralAction

Enumerator
MomentumTrapezoid 
LinearPotential 

Definition at line 158 of file LineIntegralNEB.h.

◆ LineIntegralProposalAcceptance

◆ ReferenceDiscretization

Enumerator
SymmetricResidual 
FrequencyFittedKinetic 

Definition at line 76 of file PotentialPath.h.

Function Documentation

◆ affineConstrainedQuantumBandBranch() [1/2]

ConstrainedQuantumBandBranch gpr::quantum::affineConstrainedQuantumBandBranch ( double action,
const gaussian::TwistedRestrictedResult & fluctuations,
const Eigen::MatrixXd & constraintGradients,
double quadratureWeight = 1. )
inline

Definition at line 115 of file ConstrainedQuantumProfile.h.

118{
119 if (constrained_quantum_band_detail::fullDimension(fluctuations) !=
120 constraintGradients.rows() ||
121 fluctuations.codimension != constraintGradients.cols())
122 throw std::invalid_argument(
123 "Affine constraints must match the actual restricted band");
125 action, fluctuations, fluctuations.codimension, 0, quadratureWeight,
126 affineQuantumBandLogCoarea(constraintGradients));
127}
ConstrainedQuantumBandBranch constrainedQuantumBandBranch(double action, const gaussian::TwistedRestrictedResult &fluctuations, Eigen::Index physicalCodimension, Eigen::Index integratedChartDimensions, double quadratureWeight, double logCoareaJacobian)
double affineQuantumBandLogCoarea(const Eigen::MatrixXd &constraintGradients)

◆ affineConstrainedQuantumBandBranch() [2/2]

ConstrainedQuantumBandBranch gpr::quantum::affineConstrainedQuantumBandBranch ( double action,
const gaussian::TwistedRestrictedResult & fluctuations,
const Eigen::VectorXd & constraintGradient,
double quadratureWeight = 1. )
inline

Definition at line 129 of file ConstrainedQuantumProfile.h.

132{
133 const Eigen::MatrixXd columns = constraintGradient;
134 return affineConstrainedQuantumBandBranch(action, fluctuations, columns,
135 quadratureWeight);
136}
ConstrainedQuantumBandBranch affineConstrainedQuantumBandBranch(double action, const gaussian::TwistedRestrictedResult &fluctuations, const Eigen::MatrixXd &constraintGradients, double quadratureWeight=1.)

◆ affineQuantumBandLogCoarea()

double gpr::quantum::affineQuantumBandLogCoarea ( const Eigen::MatrixXd & constraintGradients)
inline

Definition at line 62 of file ConstrainedQuantumProfile.h.

64{
65 const auto rows = constraintGradients.rows(),
66 columns = constraintGradients.cols();
67 if (columns <= 0 || rows < columns || !constraintGradients.allFinite())
68 throw std::invalid_argument(
69 "Finite independent full-band constraint covectors required");
70 Eigen::MatrixXd scaled(rows, columns);
71 double logScale = 0.;
72 for (Eigen::Index column = 0; column < columns; ++column) {
73 const double norm = constraintGradients.col(column).stableNorm();
74 if (!(norm > 0.) || !std::isfinite(norm))
75 throw std::invalid_argument(
76 "Nonzero finite constraint covectors required");
77 scaled.col(column) = constraintGradients.col(column) / norm;
78 logScale += std::log(norm);
79 }
80 const Eigen::MatrixXd gram = scaled.transpose() * scaled;
81 const Eigen::LLT<Eigen::MatrixXd> factor(gram);
82 if (factor.info() != Eigen::Success)
83 throw std::invalid_argument(
84 "Independent full-band constraint covectors required");
85 const Eigen::VectorXd diagonal =
86 factor.matrixL().toDenseMatrix().diagonal();
87 const double tolerance =
88 std::sqrt(128. * std::numeric_limits<double>::epsilon() * columns);
89 if (!diagonal.allFinite() || (diagonal.array() <= tolerance).any())
90 throw std::invalid_argument(
91 "Numerically resolved independent constraint covectors required");
92 const double result = -logScale - diagonal.array().log().sum();
93 if (!std::isfinite(result))
94 throw std::overflow_error("Unrepresentable constraint coarea");
95 return result;
96}

◆ arcActionChangeAgrees()

bool gpr::quantum::arcActionChangeAgrees ( double actual,
double predicted,
double scale )
inline

Definition at line 122 of file IndexTargetedArc.h.

123{
124 return std::isfinite(actual) && std::isfinite(predicted) &&
125 std::abs(predicted) > 128 * std::numeric_limits<double>::epsilon() *
126 std::max(1., std::abs(scale)) &&
127 std::abs(actual - predicted) <= .5 * std::abs(predicted);
128}

◆ assessReflectedPotentialPath()

PotentialPathResult gpr::quantum::assessReflectedPotentialPath ( const std::vector< Eigen::VectorXd > & halfMassPath,
const MassMetric & metric,
const std::vector< PotentialEvaluation > & physicalValues,
const PathConstraints & gauge,
const PotentialPathOptions & options = {} )
inline

Definition at line 217 of file ReflectedPotentialPath.h.

220 {})
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}
Eigen::VectorXd gradient(const Eigen::VectorXd &physicalGradient) const
Eigen::VectorXd physical(const Eigen::VectorXd &q) const
Eigen::Index dimension() const noexcept
std::vector< Eigen::MatrixXd > normals

◆ assessSurrogatePathTrust() [1/2]

SurrogatePathTrustDecision gpr::quantum::assessSurrogatePathTrust ( const PotentialPathResult & nativeCurrent,
const PotentialPathResult & nativeTrial,
const PotentialPathResult & modelCurrent,
const PotentialPathResult & modelTrial,
double radius,
double maximumRadius,
bool boundary,
bool feasible )
inline

Definition at line 76 of file SurrogatePathTrust.h.

82{
83 const double nc = surrogatePathResidualMerit(nativeCurrent),
84 nt = surrogatePathResidualMerit(nativeTrial),
85 mc = surrogatePathResidualMerit(modelCurrent),
86 mt = surrogatePathResidualMerit(modelTrial);
87 for (const auto* result: {&nativeTrial, &modelCurrent, &modelTrial})
88 if (result->fullGradient.size() != nativeCurrent.fullGradient.size() ||
89 result->fullGradient.front().size() !=
90 nativeCurrent.fullGradient.front().size())
91 throw std::invalid_argument(
92 "Matching native and model reflected residual shapes required");
93 return assessSurrogatePathTrust(nc, nt, mc, mt, radius, maximumRadius,
94 boundary, feasible);
95}
double surrogatePathResidualMerit(const PotentialPathResult &result)
SurrogatePathTrustDecision assessSurrogatePathTrust(double nativeCurrentMerit, double nativeTrialMerit, double modelCurrentMerit, double modelTrialMerit, double radius, double maximumRadius, bool boundary, bool feasible)
std::vector< Eigen::VectorXd > fullGradient

◆ assessSurrogatePathTrust() [2/2]

SurrogatePathTrustDecision gpr::quantum::assessSurrogatePathTrust ( double nativeCurrentMerit,
double nativeTrialMerit,
double modelCurrentMerit,
double modelTrialMerit,
double radius,
double maximumRadius,
bool boundary,
bool feasible )
inline

Definition at line 43 of file SurrogatePathTrust.h.

47{
48 for (double merit: {nativeCurrentMerit, nativeTrialMerit, modelCurrentMerit,
49 modelTrialMerit})
50 if (!(merit >= 0) || !std::isfinite(merit))
51 throw std::invalid_argument(
52 "Finite nonnegative trust merits required");
53 if (!(radius > 0) || !std::isfinite(radius) || !(maximumRadius >= radius) ||
54 !std::isfinite(maximumRadius))
55 throw std::invalid_argument(
56 "Finite positive trust radius within its maximum required");
57 SurrogatePathTrustDecision decision;
58 decision.actualReduction = nativeCurrentMerit - nativeTrialMerit;
59 decision.predictedReduction = modelCurrentMerit - modelTrialMerit;
60 decision.accepted = feasible && decision.actualReduction > 0;
61 decision.agreementDefined = decision.predictedReduction > 0;
62 if (decision.agreementDefined)
63 decision.agreementRatio =
64 decision.actualReduction / decision.predictedReduction;
65 decision.nextRadius = radius;
66 if (!decision.accepted ||
67 (decision.agreementDefined && decision.agreementRatio < .25))
68 decision.nextRadius = .5 * radius;
69 else if (decision.agreementDefined && decision.agreementRatio > .75 &&
70 boundary)
71 decision.nextRadius =
72 radius > maximumRadius / 2 ? maximumRadius : 2 * radius;
73 return decision;
74}

◆ boundedStationaryBathReference()

Eigen::MatrixXd gpr::quantum::boundedStationaryBathReference ( const Eigen::MatrixXd & saddleCurvature,
const Eigen::MatrixXd & reactionDirections )

Largest PSD bath bounded by the positive saddle curvature and annihilating reactionDirections. The negative saddle eigenspace stays outside the bath. Columns must be independent; a reaction span may contain positive directions.

Definition at line 13 of file BoundedStationaryBath.cpp.

15{
16 const auto d = hessian.rows(), k = directions.cols();
17 if (!d || hessian.cols() != d || !k || k > d || directions.rows() != d ||
18 !hessian.allFinite() || !directions.allFinite() ||
19 (hessian - hessian.transpose()).norm() >
20 1e-12 * std::max(1., hessian.norm()))
21 throw std::invalid_argument(
22 "Finite symmetric curvature and matching reaction span required");
23 Eigen::ColPivHouseholderQR<Eigen::MatrixXd> qr(directions);
24 if (qr.rank() != k)
25 throw std::invalid_argument("Independent reaction directions required");
26 const Eigen::MatrixXd w =
27 qr.householderQ() * Eigen::MatrixXd::Identity(d, k);
28 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eig(
29 .5 * (hessian + hessian.transpose()));
30 if (eig.info() != Eigen::Success || !eig.eigenvalues().allFinite())
31 throw std::runtime_error("Bounded bath eigensolve failed");
32 const double tol =
33 128 * std::numeric_limits<double>::epsilon() * d * hessian.norm();
34 const Eigen::Index positive = (eig.eigenvalues().array() > tol).count();
35 if (!positive) return Eigen::MatrixXd::Zero(d, d);
36 const Eigen::MatrixXd c =
37 eig.eigenvectors().rightCols(positive) *
38 eig.eigenvalues().tail(positive).cwiseSqrt().asDiagonal();
39 const Eigen::MatrixXd t = c.transpose() * w;
40 Eigen::JacobiSVD<Eigen::MatrixXd> svd(t, Eigen::ComputeFullU);
41 if (svd.info() != Eigen::Success || !svd.singularValues().allFinite())
42 throw std::runtime_error("Reaction-span bath projection failed");
43 const double threshold = 128 * std::numeric_limits<double>::epsilon() * d *
44 std::sqrt(hessian.norm());
45 const Eigen::Index removed =
46 (svd.singularValues().array() > threshold).count();
47 const Eigen::MatrixXd b = c * svd.matrixU().rightCols(positive - removed);
48 const Eigen::MatrixXd result = b * b.transpose();
49 if (!result.allFinite())
50 throw std::overflow_error("Nonfinite bounded bath curvature");
51 return result;
52}

◆ constrainedQuantumBandBranch()

ConstrainedQuantumBandBranch gpr::quantum::constrainedQuantumBandBranch ( double action,
const gaussian::TwistedRestrictedResult & fluctuations,
Eigen::Index physicalCodimension,
Eigen::Index integratedChartDimensions,
double quadratureWeight,
double logCoareaJacobian )
inline

Definition at line 98 of file ConstrainedQuantumProfile.h.

102{
103 ConstrainedQuantumBandBranch result{action,
104 fluctuations,
105 physicalCodimension,
106 integratedChartDimensions,
107 quadratureWeight,
108 logCoareaJacobian};
109 constrained_quantum_band_detail::validateShape(result);
110 return result;
111}

◆ constrainedQuantumBandFreeEnergyDifference()

double gpr::quantum::constrainedQuantumBandFreeEnergyDifference ( double logWeight,
double referenceLogWeight,
double beta )
inline

Definition at line 198 of file ConstrainedQuantumProfile.h.

200{
201 if (!std::isfinite(logWeight) || !std::isfinite(referenceLogWeight) ||
202 !(beta > 0.) || !std::isfinite(beta))
203 throw std::invalid_argument(
204 "Finite matching band logarithms and positive beta required");
205 const double result = static_cast<double>(
206 (static_cast<long double>(referenceLogWeight) - logWeight) / beta);
207 if (!std::isfinite(result))
208 throw std::overflow_error(
209 "Unrepresentable constrained-band free energy difference");
210 return result;
211}

◆ continuePotentialPathAmplitude()

AmplitudeContinuationResult gpr::quantum::continuePotentialPathAmplitude ( const std::vector< Eigen::VectorXd > & initial,
const MassMetric & metric,
const PathPotential & potential,
const AffinePathBoundary & boundary,
const PathConstraints & constraints,
const AmplitudeContinuationOptions & options = {} )

Follow conditional stationary paths on positive amplitude planes. All other constraint coordinates remain fixed. The selected amplitude column is Euclidean-unit in the full mass-weighted nodal space, as required by optimizePotentialPath. The initial target supplies its coordinate scale.

The outer root uses lambda(a)/a versus a^2. For a quartic reduced action this relation is linear. Safeguarded secants retain an ascending sign bracket away from zero; full potential callback gradients determine success. Conditional stationarity alone cannot qualify the returned solution. Neither fluctuation inertia nor a physical rate is inferred here.

Definition at line 192 of file AmplitudeContinuation.cpp.

197{
198 return continueAmplitude(initial, metric, potential, boundary, constraints,
199 options, std::nullopt);
200}

◆ continuePotentialPathAmplitudeInPhasePlane()

AmplitudeContinuationResult gpr::quantum::continuePotentialPathAmplitudeInPhasePlane ( const std::vector< Eigen::VectorXd > & initial,
const MassMetric & metric,
const PathPotential & potential,
const AffinePathBoundary & boundary,
const PathConstraints & constraints,
Eigen::Index phaseColumn,
const AmplitudeContinuationOptions & options = {} )

Find an amplitude-stationary member of a specified conditional phase family. Only the supplied phase normal may retain a force coefficient. All remaining mass-coordinate forces must meet path.forceTolerance. The returned converged flag still means full stationarity; phasePlaneStationarityQualified records the separate family condition. The caller supplies phase coverage and its coarea Jacobian when integrating this family into a rate.

Definition at line 201 of file AmplitudeContinuation.cpp.

206{
207 return continueAmplitude(initial, metric, potential, boundary, constraints,
208 options, phaseColumn);
209}

◆ cyclicQuarticReduction() [1/2]

CyclicQuarticReduction gpr::quantum::cyclicQuarticReduction ( const gaussian::Segment & link,
std::size_t nodes,
const Eigen::VectorXd & cubicVV,
double quarticVVVV )

Eliminate the centroid and second harmonic through fourth order in amplitude. cubicVV is D^3 V[.,v,v] and quarticVVVV is D^4 V[v,v,v,v], where v is the direction returned by cyclicSoftMode for this link. The physical residual potential supplies these derivatives; a quadratic reference contributes none. S(a)-S(0)=duration*(A*a^2+B*a^4)+O(a^5). A positive B defines a supercritical branch when A<0. This local expansion supplies a seed, not a qualified orbit or a rate. Native forces determine its accuracy and convergence.

◆ cyclicQuarticReduction() [2/2]

CyclicQuarticReduction gpr::quantum::cyclicQuarticReduction ( const gaussian::Segment & link,
std::size_t nodes,
const V & cubic,
double fourth )

Definition at line 81 of file CyclicSoftMode.cpp.

84{
86 result.mode = cyclicSoftMode(link, nodes);
87 if (cubic.size() != result.mode.direction.size() || !cubic.allFinite() ||
88 !std::isfinite(fourth))
89 throw std::invalid_argument(
90 "Finite matching physical third and fourth derivatives required");
91 result.centroidResponse =
92 response(result.mode.centroidCurvature, cubic, true);
94 response(result.mode.secondHarmonicCurvature, cubic, false);
96 result.quarticCoefficient = fourth / 64 +
97 cubic.dot(result.centroidResponse) / 8 +
98 cubic.dot(result.secondHarmonicResponse) / 16;
99 if (!std::isfinite(result.quarticCoefficient) ||
100 !(result.quarticCoefficient > 0))
101 throw std::invalid_argument(
102 "A positive finite reduced quartic coefficient is required");
103 if (result.quadraticCoefficient < 0) {
104 const double a2 =
105 -result.quadraticCoefficient / (2 * result.quarticCoefficient);
106 result.positiveAmplitude = std::sqrt(a2);
107 result.actionChange =
108 -result.mode.duration * result.quarticCoefficient * a2 * a2;
109 if (!std::isfinite(*result.positiveAmplitude) ||
110 !std::isfinite(*result.actionChange))
111 throw std::overflow_error("Nonfinite quartic branch prediction");
112 }
113 return result;
114}
CyclicSoftMode cyclicSoftMode(const gaussian::Segment &link, std::size_t nodes)
std::optional< double > actionChange
std::optional< double > positiveAmplitude
Eigen::MatrixXd secondHarmonicCurvature
Eigen::MatrixXd centroidCurvature

◆ cyclicQuarticSeed()

std::vector< Eigen::VectorXd > gpr::quantum::cyclicQuarticSeed ( const CyclicQuarticReduction & reduction,
double phase )

Definition at line 115 of file CyclicSoftMode.cpp.

117{
118 if (!reduction.positiveAmplitude || !std::isfinite(phase))
119 throw std::invalid_argument(
120 "A positive-amplitude branch and finite phase required");
121 const double a = *reduction.positiveAmplitude;
122 std::vector<V> result;
123 for (std::size_t j = 0; j < reduction.mode.nodes; ++j) {
124 const double theta =
125 2 * std::numbers::pi * j / reduction.mode.nodes - phase;
126 result.emplace_back(
127 a * std::cos(theta) * reduction.mode.direction +
128 a * a *
129 (reduction.centroidResponse +
130 std::cos(2 * theta) * reduction.secondHarmonicResponse));
131 }
132 return result;
133}

◆ cyclicSoftMode()

CyclicSoftMode gpr::quantum::cyclicSoftMode ( const gaussian::Segment & link,
std::size_t nodes )

Fundamental Fourier mode of a uniform cyclic link action, in mass coordinates. Curvatures divide the nodal action Hessian by the link duration. The centroid has exactly one negative direction, the second harmonic is positive, and the lowest fundamental mode is simple. At least five nodes avoid quartic aliasing.

Definition at line 43 of file CyclicSoftMode.cpp.

44{
45 const auto d = link.A.rows();
46 if (!d || nodes < 5 || !(link.duration > 0) ||
47 !std::isfinite(link.duration))
48 throw std::invalid_argument(
49 "Nonempty positive-duration link and at least five nodes required");
50 symmetric(link.A, d);
51 symmetric(link.L, d);
52 symmetric(link.rightEndpoint(), d);
53 if ((link.A - link.rightEndpoint()).norm() >
54 1e-12 * std::max(1., link.A.norm()))
55 throw std::invalid_argument(
56 "Uniform identical endpoint curvatures required");
57 const double angle = 2 * std::numbers::pi / static_cast<double>(nodes);
58 const M diagonal = link.A + link.rightEndpoint();
59 const M first = (diagonal - 2 * std::cos(angle) * link.L) / link.duration;
60 Eigen::SelfAdjointEigenSolver<M> eigen(first);
61 if (eigen.info() != Eigen::Success || !eigen.eigenvalues().allFinite())
62 throw std::runtime_error("Fundamental mode eigensolve failed");
63 const double tol = tolerance(first);
64 if (d > 1 && (eigen.eigenvalues()[1] - eigen.eigenvalues()[0] <= tol ||
65 eigen.eigenvalues()[1] <= tol))
66 throw std::invalid_argument(
67 "A simple isolated fundamental soft mode is required");
68 CyclicSoftMode result{
69 eigen.eigenvectors().col(0),
70 M((diagonal - 2 * link.L) / link.duration),
71 M((diagonal - 2 * std::cos(2 * angle) * link.L) / link.duration),
72 eigen.eigenvalues()[0],
73 link.duration * nodes,
74 nodes};
75 if (!std::isfinite(result.duration))
76 throw std::overflow_error("Nonfinite cyclic duration");
77 response(result.centroidCurvature, V::Zero(d), true);
78 response(result.secondHarmonicCurvature, V::Zero(d), false);
79 return result;
80}
const Matrix & rightEndpoint() const

◆ evaluateArcTailForceGradient()

template<class Action>
ArcTailEvaluation gpr::quantum::evaluateArcTailForceGradient ( const Action & action,
const std::vector< Eigen::VectorXd > & points,
const std::vector< PotentialEvaluation > & native,
double duration,
const ArcTailForceGradientData & data,
const std::vector< Eigen::MatrixXd > & searchHessians = {},
const std::vector< Eigen::MatrixXd > & searchThirdContractions = {} )
inline

Definition at line 177 of file ArcTailForceGradient.h.

181 {},
182 const std::vector<Eigen::MatrixXd> &searchThirdContractions = {})
183{
184 using namespace arc_force_gradient_detail;
185 if (!data.enabled) {
186 auto out = action.evaluate(points, native, duration, searchHessians);
187 out.fluctuationHessianPhysical = false;
188 return out;
189 }
190 const auto n = points.size();
191 const auto &well = action.wellCurvature();
192 const auto dimension = well.rows();
193 requireValues(points, native, dimension);
194 if (data.coordinates.size() != n || data.residualGradients.size() != n ||
195 data.residualResponses.size() != n || data.duration != duration ||
196 n != action.arcWeights().size() + 1 ||
197 (!searchHessians.empty() && searchHessians.size() != n) ||
198 (!searchThirdContractions.empty() &&
199 (searchThirdContractions.size() != n || searchHessians.empty())))
200 throw std::invalid_argument(
201 "Force-gradient data belongs to a different arc");
202 auto dressed = native;
203 auto curvature = searchHessians;
204 std::vector<V> actionGradient(n, V::Zero(dimension));
205 double actionCorrection = 0.;
206 for (std::size_t j = 0; j < n; ++j) {
207 if (data.coordinates[j].size() != dimension ||
208 (data.coordinates[j].array() != points[j].array()).any() ||
209 data.residualGradients[j].size() != dimension ||
210 !data.residualGradients[j].allFinite() ||
211 data.residualResponses[j].size() != dimension ||
212 !data.residualResponses[j].allFinite())
213 throw std::invalid_argument(
214 "Force-gradient response or geometry differs");
215 const V residual = native[j].gradient - well * points[j];
216 if ((residual.array() != data.residualGradients[j].array()).any())
217 throw std::invalid_argument(
218 "Force-gradient data belongs to different native values");
219 const double h = effectiveStep(action, j, duration);
220 const auto correction = referenceForceGradient(
221 data.residualGradients[j],
222 [&data, j](const V &) -> V { return data.residualResponses[j]; },
223 h);
224 dressed[j].energy += correction.potentialCorrection;
225 dressed[j].gradient += correction.gradientCorrection;
226 const auto &weights = action.arcWeights();
227 const double time = .5 * duration *
228 ((j ? weights[j - 1] : 0.) +
229 (j < weights.size() ? weights[j] : 0.));
230 actionCorrection += time * correction.potentialCorrection;
231 actionGradient[j] = time * correction.gradientCorrection;
232 if (!curvature.empty()) {
233 if (curvature[j].rows() != dimension ||
234 curvature[j].cols() != dimension || !curvature[j].allFinite() ||
235 (curvature[j] - curvature[j].transpose()).norm() >
236 1e-12 * std::max(1., curvature[j].norm()))
237 throw std::invalid_argument(
238 "Finite symmetric search curvature required");
239 const M residual = curvature[j] - well;
240 curvature[j].noalias() += h * h / 12. * residual * residual;
241 if (!searchThirdContractions.empty()) {
242 const auto &third = searchThirdContractions[j];
243 if (third.rows() != dimension || third.cols() != dimension ||
244 !third.allFinite() ||
245 (third - third.transpose()).norm() >
246 1e-12 * std::max(1., third.norm()))
247 throw std::invalid_argument(
248 "Finite symmetric search third contraction required");
249 curvature[j] += h * h / 12. * third;
250 }
251 }
252 }
253 auto out = action.evaluate(points, dressed, duration, curvature);
254 out.durationGradient += 2 * actionCorrection / duration;
255 out.durationHessian += 6 * actionCorrection / (duration * duration);
256 for (std::size_t j = 0; j < n; ++j)
257 out.durationCrossGradient[j] += 2 * actionGradient[j] / duration;
258 out.fluctuationHessianPhysical = false;
259 if (!std::isfinite(out.durationGradient) ||
260 !std::isfinite(out.durationHessian))
261 throw std::overflow_error("Nonfinite corrected duration derivative");
262 for (const auto &cross: out.durationCrossGradient)
263 if (!cross.allFinite())
264 throw std::overflow_error("Nonfinite corrected mixed derivative");
265 return out;
266}
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
ReferenceForceGradientValue referenceForceGradient(const Eigen::VectorXd &residualGradient, const std::function< Eigen::VectorXd(const Eigen::VectorXd &)> &residualHessianAction, double step)
std::vector< Eigen::VectorXd > coordinates
std::vector< Eigen::VectorXd > residualResponses
std::vector< Eigen::VectorXd > residualGradients

◆ evaluateCentralHessianColumns()

void gpr::quantum::evaluateCentralHessianColumns ( const std::vector< Eigen::VectorXd > & centers,
const std::vector< Eigen::Index > & columns,
double step,
const PathPotential & potential,
const std::function< void(const CentralHessianColumnBatch &)> & retain )

Ordered physical-coordinate Hessian columns at several geometries. Each positive/negative batch contains exactly the supplied centers, without an extra affine endpoint. Columns divide by the actual representable coordinate separation. The callback receives each complete column before another is evaluated, allowing persistent native-force evidence. Units follow the potential and coordinate inputs; no mass weighting, symmetrization, stationarity or index qualification is applied.

Definition at line 9 of file CentralHessianColumns.cpp.

14{
15 if (centers.empty() || columns.empty() || !(step > 0) ||
16 !std::isfinite(step) || !retain ||
17 (!potential.evaluate && !potential.evaluateBatch))
18 throw std::invalid_argument(
19 "Centers, columns, positive step, potential and retention callback "
20 "required");
21 const auto d = centers.front().size();
22 if (!d) throw std::invalid_argument("Nonempty center coordinates required");
23 for (const auto& center: centers)
24 if (center.size() != d || !center.allFinite())
25 throw std::invalid_argument("Matching finite centers required");
26 std::set<Eigen::Index> unique;
27 for (auto column: columns)
28 if (column < 0 || column >= d || !unique.insert(column).second)
29 throw std::invalid_argument(
30 "Distinct in-range Hessian columns required");
31 auto evaluate = [&](const std::vector<Eigen::VectorXd>& positions) {
32 std::vector<PotentialEvaluation> values;
33 if (potential.evaluateBatch)
34 values = potential.evaluateBatch(positions);
35 else
36 for (const auto& point: positions)
37 values.push_back(potential.evaluate(point));
38 if (values.size() != positions.size())
39 throw std::runtime_error("Hessian batch point count differs");
40 for (const auto& value: values)
41 if (!std::isfinite(value.energy) || value.gradient.size() != d ||
42 !value.gradient.allFinite())
43 throw std::runtime_error(
44 "Invalid physical value in Hessian batch");
45 return values;
46 };
47 for (auto column: columns) {
48 CentralHessianColumnBatch result;
49 result.column = column;
50 result.positivePositions = centers;
51 result.negativePositions = centers;
52 for (std::size_t j = 0; j < centers.size(); ++j) {
53 result.positivePositions[j][column] += step;
54 result.negativePositions[j][column] -= step;
55 const double separation = result.positivePositions[j][column] -
56 result.negativePositions[j][column];
57 if (!(separation > 0) || !std::isfinite(separation) ||
58 !result.positivePositions[j].allFinite() ||
59 !result.negativePositions[j].allFinite())
60 throw std::invalid_argument(
61 "Finite representable positive displacement separation "
62 "required");
63 result.separations.push_back(separation);
64 }
65 result.positive = evaluate(result.positivePositions);
66 result.negative = evaluate(result.negativePositions);
67 for (std::size_t j = 0; j < centers.size(); ++j) {
68 result.columns.emplace_back(
69 (result.positive[j].gradient - result.negative[j].gradient) /
70 result.separations[j]);
71 if (!result.columns.back().allFinite())
72 throw std::overflow_error("Nonfinite central Hessian column");
73 }
74 retain(result);
75 }
76}
std::function< std::vector< PotentialEvaluation >(const std::vector< Eigen::VectorXd > &)> evaluateBatch
std::function< PotentialEvaluation(const Eigen::VectorXd &)> evaluate

◆ evaluateGaussianPolynomial()

GaussianPolynomialMoments gpr::quantum::evaluateGaussianPolynomial ( const GaussianLaw & law,
const SparsePolynomial & polynomial,
std::optional< long double > eventProbabilityBound )

Definition at line 153 of file GaussianPolynomial.cpp.

156{
157 if (std::fegetround() != FE_TONEAREST)
158 throw std::runtime_error(
159 "Gaussian polynomial arithmetic requires round-to-nearest");
161 validateLaw(law, result);
162 const auto dimension = static_cast<std::size_t>(law.mean.size());
163 for (const auto& term: polynomial) {
164 if (!std::isfinite(term.coefficient) || term.powers.size() != dimension)
165 throw std::invalid_argument(
166 "Polynomial coefficient or multi-index dimension is invalid");
167 for (unsigned power: term.powers)
168 if (power > std::numeric_limits<unsigned>::max() / 2)
169 throw std::overflow_error(
170 "Polynomial square multi-index exceeds its integer range");
171 }
172 Moments moments(law);
173 for (const auto& term: polynomial) {
174 if (term.coefficient == 0) continue;
175 result.first = add(result.first, multiply({term.coefficient, 0},
176 moments.get(term.powers)));
177 for (const auto& other: polynomial) {
178 if (other.coefficient == 0) continue;
179 Powers combined = term.powers;
180 for (std::size_t i = 0; i < dimension; ++i)
181 combined[i] += other.powers[i];
182 result.second =
183 add(result.second, multiply(multiply({term.coefficient, 0},
184 {other.coefficient, 0}),
185 moments.get(std::move(combined))));
186 }
187 }
188 if (addUp(result.second.value, result.second.absoluteRoundoffBound) < 0)
189 throw std::runtime_error("Negative Gaussian polynomial second moment");
192 if (eventProbabilityBound)
194 weightedEventBound(result, *eventProbabilityBound);
195 return result;
196}
double addUp(double a, double b)
long double weightedEventBound(const GaussianPolynomialMoments &moments, long double probabilityBound)
std::optional< long double > weightedEventAbsoluteBound

◆ evaluateJacobiPath()

JacobiPathEvaluation gpr::quantum::evaluateJacobiPath ( const std::vector< Eigen::VectorXd > & points,
const std::vector< PotentialEvaluation > & native,
double energy )
inline

Definition at line 74 of file JacobiAction.h.

77{
78 if (points.size() < 2 || native.size() != points.size())
79 throw std::invalid_argument(
80 "Matching Jacobi path nodes and native values required");
82 out.gradient.assign(points.size(),
83 Eigen::VectorXd::Zero(points.front().size()));
84 for (std::size_t j = 0; j + 1 < points.size(); ++j) {
85 const auto link = jacobiSegment(points[j], points[j + 1], native[j],
86 native[j + 1], energy);
87 out.action += link.action;
88 out.traversalTime += link.traversalTime;
89 out.gradient[j] += link.leftGradient;
90 out.gradient[j + 1] += link.rightGradient;
91 }
92 return out;
93}
JacobiSegment jacobiSegment(const Eigen::VectorXd &left, const Eigen::VectorXd &right, const PotentialEvaluation &vl, const PotentialEvaluation &vr, double energy)

◆ evaluateLineIntegralNEB()

LineIntegralNEBState gpr::quantum::evaluateLineIntegralNEB ( const std::vector< Eigen::VectorXd > & q,
const std::vector< PotentialEvaluation > & values,
double energy,
double spring = 1.,
double contour = 10.,
double hbar = 1.,
LineIntegralAction action = LineIntegralAction::MomentumTrapezoid,
bool jctcCompatible = false,
double contourRight = 0.,
double actionForceCutoff = 1e-4 )
inline

Definition at line 159 of file LineIntegralNEB.h.

166{
169 throw std::invalid_argument("Unknown LI-NEB action quadrature");
170 if (jctcCompatible && action != LineIntegralAction::MomentumTrapezoid)
171 throw std::invalid_argument(
172 "JCTC LI-NEB requires momentum-trapezoid action");
173 const std::size_t n = q.size();
174 if (n < 3 || values.size() != n || q.front().size() < 1 ||
175 !std::isfinite(energy) || !(spring > 0) || !(contour > 0) ||
176 !(hbar > 0) || !std::isfinite(spring) || !std::isfinite(contour) ||
177 !std::isfinite(hbar))
178 throw std::invalid_argument(
179 "Finite LI-NEB parameters and at least three matching images "
180 "required");
181 std::vector<double> xi(n), length(n - 1);
182 for (std::size_t j = 0; j < n; ++j) {
183 if (q[j].size() != q.front().size() ||
184 values[j].gradient.size() != q.front().size() ||
185 !q[j].allFinite() || !values[j].gradient.allFinite() ||
186 !std::isfinite(values[j].energy))
187 throw std::invalid_argument(
188 "Finite matching mass-coordinate energies and gradients "
189 "required");
190 if (j && j + 1 < n && !jctcCompatible) {
191 if (!(values[j].energy > energy))
192 throw std::domain_error(
193 "Interior LI-NEB image leaves the forbidden region");
194 }
195 xi[j] = std::sqrt(2 * std::max(0., values[j].energy - energy)) / hbar;
196 if (j) {
197 length[j - 1] = (q[j] - q[j - 1]).norm();
198 if (!(length[j - 1] > 0) || !std::isfinite(length[j - 1]))
199 throw std::domain_error(
200 "Distinct finite adjacent LI-NEB images required");
201 }
202 }
204 out.turningOrientationsQualified = true;
205 out.force.resize(n);
206 out.actionForce.assign(n, Eigen::VectorXd::Zero(q.front().size()));
209 auto contourValues = values;
210 contourValues.front().energy = energy;
211 contourValues.back().energy = energy;
212 exact = evaluateJacobiPath(q, contourValues, energy);
213 out.abbreviatedAction = exact.action;
214 } else {
215 for (std::size_t j = 0; j + 1 < n; ++j)
216 out.abbreviatedAction +=
217 .5 * hbar * (xi[j] + xi[j + 1]) * length[j];
218 }
219 const auto tangents = jctcCompatible
220 ? detail::lineIntegralENOTangents(q, values)
221 : std::vector<Eigen::VectorXd>{};
222 for (std::size_t j = 1; j + 1 < n; ++j) {
223 const Eigen::VectorXd left = (q[j] - q[j - 1]) / length[j - 1];
224 const Eigen::VectorXd right = (q[j + 1] - q[j]) / length[j];
225 const Eigen::VectorXd tangent =
226 jctcCompatible ? tangents[j]
227 : detail::lineIntegralUnitTangent(q, values, j);
228 Eigen::VectorXd actionForce;
229 if (action == LineIntegralAction::LinearPotential)
230 actionForce = -exact.gradient[j] / hbar;
231 else {
232 const double gap = values[j].energy - energy;
233 Eigen::VectorXd potentialForce =
234 Eigen::VectorXd::Zero(q.front().size());
235 if (!jctcCompatible || gap >= actionForceCutoff)
236 potentialForce = -.5 * (length[j - 1] + length[j]) /
237 (hbar * hbar * xi[j]) * values[j].gradient;
238 actionForce = potentialForce - .5 * (xi[j] + xi[j - 1]) * left +
239 .5 * (xi[j + 1] + xi[j]) * right;
240 }
241 out.actionForce[j] = actionForce;
242 }
243 std::vector<Eigen::VectorXd> smoothed = out.actionForce;
244 if (jctcCompatible) {
245 std::vector<double> amplitude(n, 0.);
246 for (std::size_t j = 1; j + 1 < n; ++j)
247 amplitude[j] = out.actionForce[j].norm();
248 for (std::size_t j = 1; j + 1 < n; ++j) {
249 const std::size_t first = j > 1 ? j - 1 : 1,
250 last = std::min(j + 1, n - 2);
251 double mean = 0.;
252 for (std::size_t k = first; k <= last; ++k)
253 mean += amplitude[k];
254 mean /= double(last - first + 1);
255 if (amplitude[j] > 0)
256 smoothed[j] *= mean / amplitude[j];
257 else
258 smoothed[j].setZero();
259 const Eigen::VectorXd tangent = tangents[j];
260 const Eigen::VectorXd rawTransverse =
261 out.actionForce[j] - out.actionForce[j].dot(tangent) * tangent;
262 out.transverseForceSum += rawTransverse.norm();
263 out.force[j] = smoothed[j] - smoothed[j].dot(tangent) * tangent +
264 spring * (length[j] - length[j - 1]) * tangent;
265 }
266 } else {
267 for (std::size_t j = 1; j + 1 < n; ++j) {
268 const Eigen::VectorXd tangent =
269 detail::lineIntegralUnitTangent(q, values, j);
270 const Eigen::VectorXd raw = out.actionForce[j];
271 out.force[j] = raw - raw.dot(tangent) * tangent +
272 spring * (length[j] - length[j - 1]) * tangent;
273 out.transverseForceSum += (raw - raw.dot(tangent) * tangent).norm();
274 }
275 }
276 for (const std::size_t j: {std::size_t(0), n - 1}) {
277 const double norm = values[j].gradient.norm();
278 if (!(norm > 0))
279 throw std::domain_error(
280 "Turning contour requires a nonzero endpoint gradient");
281 const Eigen::VectorXd normal = values[j].gradient / norm;
282 const std::size_t adjacent = j == 0 ? 1 : n - 2;
283 const Eigen::VectorXd direction =
284 (q[adjacent] - q[j]) / (q[adjacent] - q[j]).norm();
285 Eigen::VectorXd pull;
286 if (jctcCompatible) {
287 pull = direction * smoothed[adjacent].norm();
288 } else
289 pull = spring * (q[j == 0 ? 1 : n - 2] - q[j]);
290 out.turningOrientationsQualified =
291 out.turningOrientationsQualified && normal.dot(direction) > 0;
292 // Knarr's contour endpoint uses force/|force|, hence this minus sign
293 // with the positive energy gradient drives V towards E on either side.
294 const double endpointContour =
295 j == 0 || contourRight == 0. ? contour : contourRight;
296 out.force[j] = pull - pull.dot(normal) * normal -
297 endpointContour * (values[j].energy - energy) * normal;
298 out.endpointEnergyError = std::max(out.endpointEnergyError,
299 std::abs(values[j].energy - energy));
300 }
301 for (const auto& f: out.force) {
302 if (!f.allFinite()) throw std::runtime_error("Nonfinite LI-NEB force");
303 out.maximumForce = std::max(out.maximumForce, f.norm());
304 }
305 return out;
306}
JacobiPathEvaluation evaluateJacobiPath(const std::vector< Eigen::VectorXd > &points, const std::vector< PotentialEvaluation > &native, double energy)

◆ evaluateLineIntegralString()

LineIntegralNEBState gpr::quantum::evaluateLineIntegralString ( const std::vector< Eigen::VectorXd > & q,
const std::vector< PotentialEvaluation > & values,
double energy,
double spring = 1.,
double contour = 10.,
double hbar = 1.,
LineIntegralAction action = LineIntegralAction::MomentumTrapezoid )
inline

Definition at line 94 of file LineIntegralString.h.

99{
100 auto state = evaluateLineIntegralNEB(q, values, energy, spring, contour,
101 hbar, action);
102 const auto actionForce =
103 lineIntegralStringActionForces(q, values, energy, hbar, action);
104 state.maximumForce = 0.;
105 for (std::size_t j = 1; j + 1 < q.size(); ++j) {
106 const Eigen::VectorXd left = (q[j] - q[j - 1]).normalized();
107 const Eigen::VectorXd right = (q[j + 1] - q[j]).normalized();
108 Eigen::VectorXd tangent = left + right;
109 const double tangentNorm = tangent.norm();
110 if (!(tangentNorm > 1e-12) || !std::isfinite(tangentNorm))
111 throw std::domain_error(
112 "Line-integral string requires a resolved geometric tangent");
113 tangent /= tangentNorm;
114 state.force[j] = actionForce[j] - actionForce[j].dot(tangent) * tangent;
115 }
116 for (const std::size_t j: {std::size_t{0}, q.size() - 1}) {
117 const auto neighbour = j == 0 ? std::size_t{1} : q.size() - 2;
118 const Eigen::VectorXd gradient = values[j].gradient;
119 const double norm = gradient.norm();
120 if (!(norm > 0.) || !std::isfinite(norm))
121 throw std::domain_error(
122 "Line-integral string turning point requires a finite normal");
123 const Eigen::VectorXd normal = gradient / norm;
124 Eigen::VectorXd tangent = q[neighbour] - q[j];
125 const double tangentNorm = tangent.norm();
126 if (!(tangentNorm > 0.) || !std::isfinite(tangentNorm))
127 throw std::domain_error(
128 "Line-integral string endpoint requires a finite tangent");
129 // A turning point meets the contour along its normal. The spring pull
130 // towards the neighbour, projected onto the contour, vanishes only
131 // there and keeps its size while the interior converges, so the
132 // stopping test sees a misaligned endpoint.
133 const Eigen::VectorXd pull = spring * (q[neighbour] - q[j]);
134 state.force[j] = pull - pull.dot(normal) * normal -
135 contour * (values[j].energy - energy) * normal;
136 }
137 for (const auto& force: state.force) {
138 if (!force.allFinite())
139 throw std::runtime_error("Nonfinite line-integral string force");
140 state.maximumForce = std::max(state.maximumForce, force.norm());
141 }
142 return state;
143}
std::vector< Eigen::VectorXd > lineIntegralStringActionForces(const std::vector< Eigen::VectorXd > &q, const std::vector< PotentialEvaluation > &values, double energy, double hbar, LineIntegralAction action)
LineIntegralNEBState evaluateLineIntegralNEB(const std::vector< Eigen::VectorXd > &q, const std::vector< PotentialEvaluation > &values, double energy, double spring=1., double contour=10., double hbar=1., LineIntegralAction action=LineIntegralAction::MomentumTrapezoid, bool jctcCompatible=false, double contourRight=0., double actionForceCutoff=1e-4)

◆ evaluateZeroEnergyGeodesic() [1/4]

ZeroEnergyGeodesicEvaluation gpr::quantum::evaluateZeroEnergyGeodesic ( const Eigen::MatrixXd & positiveWellRoot,
double radius,
const std::vector< Eigen::VectorXd > & path,
const std::vector< PotentialEvaluation > & native,
double meshStiffness,
const std::vector< Eigen::MatrixXd > & searchHessians,
const std::vector< double > & meshWeights )

◆ evaluateZeroEnergyGeodesic() [2/4]

ZeroEnergyGeodesicEvaluation gpr::quantum::evaluateZeroEnergyGeodesic ( const Eigen::MatrixXd & positiveWellRoot,
double radius,
const std::vector< Eigen::VectorXd > & path,
const std::vector< PotentialEvaluation > & native,
double meshStiffness = 1.,
const std::vector< Eigen::MatrixXd > & searchHessians = {} )

◆ evaluateZeroEnergyGeodesic() [3/4]

ZeroEnergyGeodesicEvaluation gpr::quantum::evaluateZeroEnergyGeodesic ( const M & omega,
double radius,
const std::vector< V > & path,
const std::vector< PotentialEvaluation > & native,
double stiffness,
const std::vector< M > & hessians )

Definition at line 46 of file ZeroEnergyGeodesic.cpp.

50{
51 return evaluateZeroEnergyGeodesic(omega, radius, path, native, stiffness,
52 hessians, {});
53}
ZeroEnergyGeodesicEvaluation evaluateZeroEnergyGeodesic(const M &omega, double radius, const std::vector< V > &path, const std::vector< PotentialEvaluation > &native, double stiffness, const std::vector< M > &hessians)

◆ evaluateZeroEnergyGeodesic() [4/4]

ZeroEnergyGeodesicEvaluation gpr::quantum::evaluateZeroEnergyGeodesic ( const M & omega,
double radius,
const std::vector< V > & path,
const std::vector< PotentialEvaluation > & native,
double stiffness,
const std::vector< M > & hessians,
const std::vector< double > & meshWeights )

Definition at line 54 of file ZeroEnergyGeodesic.cpp.

58{
59 const auto n = path.size();
60 require(n >= 3 && native.size() == n &&
61 (hessians.empty() || hessians.size() == n),
62 "Matching geodesic nodes and native values required");
63 require(meshWeights.empty() || meshWeights.size() + 1 == n,
64 "One graded mesh weight per geodesic link required");
65 for (double weight: meshWeights)
66 require(weight > 0 && std::isfinite(weight),
67 "Positive finite geodesic mesh weights required");
68 const auto d = path.front().size();
69 const M identity = M::Identity(d, d);
70 require(d > 0 && omega.rows() == d && omega.cols() == d &&
71 omega.allFinite() &&
72 (omega - omega.transpose()).norm() <=
73 1e-12 * std::max(1., omega.norm()) &&
74 radius > 0 && std::isfinite(radius) && stiffness > 0 &&
75 std::isfinite(stiffness),
76 "Positive geodesic well, radius and mesh scale required");
77 Eigen::SelfAdjointEigenSolver<M> spectrum(omega);
78 require(spectrum.info() == Eigen::Success &&
79 spectrum.eigenvalues().minCoeff() > 0,
80 "Positive harmonic well root required");
81 for (std::size_t j = 0; j < n; ++j) {
82 require(path[j].size() == d && path[j].allFinite() &&
83 native[j].gradient.size() == d &&
84 native[j].gradient.allFinite() &&
85 std::isfinite(native[j].energy),
86 "Invalid native geodesic point");
87 if (j + 1 < n && !(native[j].energy > 0))
88 throw std::domain_error(
89 "Interior geodesic nodes must remain in the forbidden region");
90 if (!hessians.empty())
91 require(hessians[j].rows() == d && hessians[j].cols() == d &&
92 hessians[j].allFinite() &&
93 (hessians[j] - hessians[j].transpose()).norm() <
94 1e-12 * std::max(1., hessians[j].norm()),
95 "Invalid geodesic search curvature");
96 }
97 std::vector<double> lengths;
98 std::vector<V> unit;
99 for (std::size_t j = 0; j + 1 < n; ++j) {
100 const V delta = path[j + 1] - path[j];
101 const double length = delta.norm();
102 require(length > 0 && std::isfinite(length),
103 "Distinct finite geodesic nodes required");
104 lengths.push_back(length);
105 unit.push_back(delta / length);
106 }
107 ZeroEnergyGeodesicEvaluation out;
108 out.residual.assign(n, V::Zero(d));
109 if (!hessians.empty()) {
110 out.lower.assign(n, M::Zero(d, d));
111 out.diagonal = out.lower;
112 out.upper = out.lower;
113 }
114 const double r = path.front().norm();
115 require(r > 0 && std::isfinite(r),
116 "Nonzero harmonic matching cut required");
117 const V radial = path.front() / r, t0 = unit.front();
118 const M pr = identity - radial * radial.transpose();
119 const double p = std::sqrt(2 * native.front().energy),
120 frequency = omega.trace() / d;
121 const V momentum = omega * path.front() - p * t0;
122 const V angular = pr * momentum;
123 out.residual.front() = angular + frequency * (r - radius) * radial;
124 out.momentumResidual = angular.norm();
125 out.radiusResidual = std::abs(r - radius);
126 out.tailPointsOutward = (omega * path.front()).dot(t0) > 0;
127 if (!hessians.empty())
128 for (int side = 0; side < 2; ++side) {
129 const M dq = M((side == 0 ? 1. : 0.) * identity);
130 const M dr = pr * dq / r, dt = (identity - t0 * t0.transpose()) /
131 lengths.front() *
132 ((side == 0 ? -1. : 1.) * identity);
133 const M dm = omega * dq -
134 t0 * native.front().gradient.transpose() * dq / p -
135 p * dt;
136 M block = pr * dm -
137 (momentum.dot(radial) * identity +
138 radial * momentum.transpose()) *
139 dr +
140 frequency * (radial * radial.transpose() * dq +
141 (r - radius) * dr);
142 if (side == 0)
143 out.diagonal.front() = block;
144 else
145 out.upper.front() = block;
146 }
147 for (std::size_t j = 1; j + 1 < n; ++j) {
148 const double a = lengths[j - 1], b = lengths[j], sum = a + b;
149 const V u = unit[j - 1], v = unit[j], both = u + v;
150 const double norm = both.norm();
151 require(norm > 1e-12,
152 "Geodesic links cannot reverse at an interior node");
153 V t = both / norm, kappa = 2 * (v - u) / sum;
154 double mesh = a - b;
155 MeshGeometry graded;
156 if (!meshWeights.empty()) {
157 graded = meshGeometry(path[j - 1], path[j], path[j + 1],
158 meshWeights[j - 1], meshWeights[j]);
159 t = graded.tangent;
160 kappa = graded.curvature;
161 mesh = 2 * (graded.right * a - graded.left * b) /
162 (graded.left + graded.right);
163 }
164 const V g = native[j].gradient;
165 const M projection = identity - t * t.transpose();
166 const V force = projection * g - 2 * native[j].energy * kappa;
167 out.forceResidual = std::max(out.forceResidual, force.norm());
168 out.meshResidual = std::max(out.meshResidual, std::abs(mesh));
169 out.residual[j] = force + stiffness * mesh * t;
170 if (!hessians.empty())
171 for (int side = -1; side <= 1; ++side) {
172 const M prev = M((side == -1 ? 1. : 0.) * identity),
173 here = M((side == 0 ? 1. : 0.) * identity),
174 next = M((side == 1 ? 1. : 0.) * identity);
175 const M du = (identity - u * u.transpose()) / a * (here - prev),
176 dv = (identity - v * v.transpose()) / b * (next - here);
177 M dt = projection * (du + dv) / norm;
178 const Eigen::RowVectorXd dl = u.transpose() * (here - prev) +
179 v.transpose() * (next - here);
180 Eigen::RowVectorXd dc = u.transpose() * (here - prev) -
181 v.transpose() * (next - here);
182 M dk = 2 * (dv - du) / sum - kappa * dl / sum;
183 if (!meshWeights.empty()) {
184 const double hm = graded.left, hp = graded.right,
185 speed = graded.speed;
186 const M dw =
187 (hp / hm * (here - prev) + hm / hp * (next - here)) /
188 (hm + hp);
189 const M dz = 2 * ((next - here) / hp - (here - prev) / hm) /
190 (hm + hp);
191 const V second = 2 *
192 ((path[j + 1] - path[j]) / hp -
193 (path[j] - path[j - 1]) / hm) /
194 (hm + hp);
195 dt = projection * dw / speed;
196 dk = (projection * dz -
197 (second.dot(t) * identity + t * second.transpose()) *
198 dt) /
199 (speed * speed) -
200 2 * kappa * (t.transpose() * dw) / speed;
201 dc = 2 *
202 (hp * u.transpose() * (here - prev) -
203 hm * v.transpose() * (next - here)) /
204 (hm + hp);
205 }
206 const M block = projection * hessians[j] * here -
207 (g.dot(t) * identity + t * g.transpose()) * dt -
208 2 * kappa * g.transpose() * here -
209 2 * native[j].energy * dk +
210 stiffness * (t * dc + mesh * dt);
211 if (side == -1)
212 out.lower[j] = block;
213 else if (side == 0)
214 out.diagonal[j] = block;
215 else
216 out.upper[j] = block;
217 }
218 }
219 const auto last = n - 1;
220 const V t = unit.back(), g = native.back().gradient;
221 const M projection = identity - t * t.transpose();
222 const double length = lengths.back(), energy = native.back().energy;
223 const V transverse = projection * g;
224 out.residual.back() = transverse + (energy / length) * t;
225 out.forceResidual = std::max(out.forceResidual, transverse.norm());
226 out.turningEnergyResidual = std::abs(energy);
227 out.turningPointsInward = g.dot(t) < 0;
228 if (!hessians.empty())
229 for (int side = 0; side < 2; ++side) {
230 const M here = M((side == 1 ? 1. : 0.) * identity);
231 const M delta = M((side == 1 ? 1. : -1.) * identity),
232 dt = projection * delta / length;
233 const Eigen::RowVectorXd dl = t.transpose() * delta;
234 const M block =
235 projection * hessians[last] * here +
236 ((-g.dot(t) + energy / length) * identity - t * g.transpose()) *
237 dt +
238 t * (g.transpose() * here / length -
239 energy * dl / (length * length));
240 if (side == 0)
241 out.lower.back() = block;
242 else
243 out.diagonal.back() = block;
244 }
245 for (const auto& value: out.residual)
246 require(value.allFinite(), "Nonfinite geodesic residual");
247 return out;
248}

◆ findJacobiTurningPoint()

JacobiTurningPoint gpr::quantum::findJacobiTurningPoint ( const Eigen::VectorXd & left,
const Eigen::VectorXd & right,
double energy,
const std::function< PotentialEvaluation(const Eigen::VectorXd &)> & evaluate,
double energyTolerance = 1e-9,
std::size_t maximumEvaluations = 64 )
inline

Definition at line 27 of file JacobiTurningPoint.h.

31{
32 if (left.size() < 1 || right.size() != left.size() || !left.allFinite() ||
33 !right.allFinite())
34 throw std::invalid_argument(
35 "Matching finite turning-point coordinates required");
36 const Eigen::VectorXd direction = right - left;
37 if (!(direction.norm() > 0) || !std::isfinite(direction.norm()) ||
38 !direction.allFinite() || !std::isfinite(energy) ||
39 !(energyTolerance > 0) || !std::isfinite(energyTolerance) ||
40 maximumEvaluations < 2 || !evaluate)
41 throw std::invalid_argument(
42 "Finite distinct turning bracket, energy scale and native callback "
43 "required");
45 struct Point {
46 double t{}, f{}, slope{};
47 PotentialEvaluation native;
48 };
49 auto measure = [&](double t) {
50 const Eigen::VectorXd q = left + t * direction;
51 auto native = evaluate(q);
52 ++out.evaluations;
53 if (!std::isfinite(native.energy) ||
54 native.gradient.size() != left.size() ||
55 !native.gradient.allFinite())
56 throw std::runtime_error(
57 "Turning-point callback returned invalid native energy or "
58 "gradient");
59 return Point{t, native.energy - energy, native.gradient.dot(direction),
60 std::move(native)};
61 };
62 auto a = measure(0.), b = measure(1.);
63 auto best = std::abs(a.f) <= std::abs(b.f) ? a : b;
64 if (std::abs(best.f) > energyTolerance &&
65 std::signbit(a.f) == std::signbit(b.f))
66 throw std::invalid_argument(
67 "Measured endpoint energies do not bracket the turning energy");
68 double previousStep = 1.;
69 while (std::abs(best.f) > energyTolerance &&
70 out.evaluations < maximumEvaluations) {
71 const double width = b.t - a.t;
72 double next = best.t - best.f / best.slope;
73 const double margin = 16 * std::numeric_limits<double>::epsilon() *
74 std::max(1., std::abs(best.t));
75 if (!std::isfinite(next) || next <= a.t + margin ||
76 next >= b.t - margin || std::abs(next - best.t) > .5 * previousStep)
77 next = .5 * (a.t + b.t);
78 if (!(next > a.t && next < b.t)) {
79 out.failure =
80 "Turning-energy bracket is unresolved at floating-point "
81 "precision";
82 break;
83 }
84 previousStep = width;
85 auto point = measure(next);
86 if (std::signbit(point.f) == std::signbit(a.f))
87 a = point;
88 else
89 b = point;
90 best = std::abs(a.f) <= std::abs(b.f) ? a : b;
91 }
92 out.parameter = best.t;
93 out.point = left + best.t * direction;
94 out.native = best.native;
95 out.energyResidual = std::abs(best.f);
96 out.bracketWidth = (b.t - a.t) * direction.norm();
97 out.converged = out.energyResidual <= energyTolerance;
98 if (!out.converged && out.failure.empty())
99 out.failure = "Maximum native turning-point evaluations reached";
100 return out;
101}
VecchiaResult evaluate(const Eigen::MatrixXd &points, const Eigen::VectorXd &y, double lengthscale, double noise, int max_neighbours)

◆ fixedTimeArcOptions()

ArcTailSearchOptions gpr::quantum::fixedTimeArcOptions ( )
inline

Definition at line 78 of file FixedTimeArc.h.

◆ frequencyFittedKinetic()

gaussian::Segment gpr::quantum::frequencyFittedKinetic ( const Eigen::MatrixXd & curvature,
double duration )

Positive kinetic coupling fitted to one fixed physical curvature. The returned link has A=L and no physical potential term. Adding h*V/2 at each endpoint preserves every constant stationary point. Its untwisted harmonic trace is exact when the physical Hessian equals the fitting curvature. Negative modes require h*sqrt(-lambda)<pi. Anharmonic paths and reference ratios still require discretization comparisons.

Definition at line 10 of file FrequencyFittedKinetic.cpp.

12{
13 const auto d = curvature.rows();
14 if (!d || curvature.cols() != d || !curvature.allFinite() || !(h > 0) ||
15 !std::isfinite(h) ||
16 (curvature - curvature.transpose()).norm() >
17 1e-12 * std::max(1., curvature.norm()))
18 throw std::invalid_argument(
19 "Finite symmetric fitting curvature and positive duration "
20 "required");
21 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigen(
22 .5 * (curvature + curvature.transpose()));
23 if (eigen.info() != Eigen::Success || !eigen.eigenvalues().allFinite())
24 throw std::runtime_error(
25 "Frequency-fitted curvature eigensolve failed");
26 Eigen::VectorXd coupling(d);
27 double logarithm = 0, caustic = std::numeric_limits<double>::infinity();
28 for (Eigen::Index i = 0; i < d; ++i) {
29 const double lambda = eigen.eigenvalues()[i],
30 x = .5 * h * std::sqrt(std::abs(lambda));
31 if (!std::isfinite(x))
32 throw std::overflow_error("Unrepresentable fitted phase");
33 double ratio = 1;
34 if (lambda < 0) {
35 if (!(x < std::numbers::pi / 2))
36 throw std::domain_error(
37 "Fitted unstable link reaches its reference caustic");
38 if (x > 0) ratio = x / std::sin(x);
39 caustic = std::min(caustic, std::numbers::pi - 2 * x);
40 } else if (x > 0) {
41 ratio = x < 20 ? x / std::sinh(x)
42 : 2 * x * std::exp(-x) / (-std::expm1(-2 * x));
43 }
44 coupling[i] = ratio * ratio / h;
45 if (!(coupling[i] > 0) || !std::isfinite(coupling[i]))
46 throw std::overflow_error(
47 "Unrepresentable positive fitted kinetic coupling");
48 logarithm += std::log(coupling[i]);
49 }
50 Eigen::MatrixXd l = eigen.eigenvectors() * coupling.asDiagonal() *
51 eigen.eigenvectors().transpose();
52 l = (.5 * l + .5 * l.transpose()).eval();
53 if (!l.allFinite() || !std::isfinite(logarithm))
54 throw std::overflow_error("Nonfinite fitted kinetic link");
55 return {l, l, logarithm, h, caustic, {}};
56}
@ x
Definition Enums.h:28
STL namespace.

◆ geodesicMeshConstraints()

Eigen::VectorXd gpr::quantum::geodesicMeshConstraints ( const std::vector< Eigen::VectorXd > & path,
const std::vector< double > & weights = {} )
inline

Definition at line 80 of file GeodesicMeshProjection.h.

82 {})
83{
84 return meshprojection_detail::geometry(path, weights).constraint;
85}

◆ indexOneArcKernel()

IndexTargetedArcKernel gpr::quantum::indexOneArcKernel ( const std::vector< gaussian::Segment > & segments,
const Eigen::MatrixXd & normal )
inline

Definition at line 23 of file IndexTargetedArc.h.

26{
27 using M = Eigen::MatrixXd;
28 if (segments.empty())
29 throw std::invalid_argument("Nonempty arc search kernel required");
30 const auto d = segments.front().A.rows();
31 if (d < 1 || normal.rows() != Eigen::Index(segments.size()) * d ||
32 normal.cols() < 1 || !normal.allFinite())
33 throw std::invalid_argument(
34 "Matching finite arc phase normals required");
36 double scale = 1.;
37 for (const auto& link: segments)
38 scale = std::max(scale, link.A.cwiseAbs().maxCoeff() +
39 link.rightEndpoint().cwiseAbs().maxCoeff() +
40 2 * link.L.cwiseAbs().maxCoeff());
41 auto assess = [&](double shift) {
42 result.segments = segments;
43 for (auto& link: result.segments) {
44 const M right = link.rightEndpoint();
45 link.rightA = right;
46 link.A.diagonal().array() += shift;
47 }
48 ++result.factorizations;
49 const auto spectrum = gaussian::restrictedTraceDeterminant(
50 result.segments, M::Identity(d, d), normal);
51 if (spectrum.inertia.zero || spectrum.unresolvedBorderEigenvalues)
52 throw std::runtime_error(
53 "Arc shift lies on an unresolved eigenvalue");
54 result.shift = shift;
55 return spectrum.inertia.negative;
56 };
57 const auto original = assess(0.);
58 if (original == 1) return result;
59 double low = 0., high = 0.;
60 bool bracketed = false;
61 for (unsigned k = 0; k < 48; ++k) {
62 const double trial = original > 1 ? scale : -scale;
63 const auto negative = assess(trial);
64 if (negative == 1) return result;
65 if ((original > 1 && negative == 0) ||
66 (original == 0 && negative > 1)) {
67 low = original > 1 ? 0. : trial;
68 high = original > 1 ? trial : 0.;
69 bracketed = true;
70 break;
71 }
72 scale *= 2;
73 }
74 if (!bracketed)
75 throw std::runtime_error("Cannot bracket an index-one arc kernel");
76 for (unsigned k = 0; k < 80; ++k) {
77 const double middle = low + .5 * (high - low);
78 if (middle == low || middle == high) break;
79 std::size_t negative;
80 try {
81 negative = assess(middle);
82 } catch (const std::runtime_error&) {
83 const double offset = 256 * std::numeric_limits<double>::epsilon() *
84 std::max({1., scale, std::abs(middle)});
85 const double adjacent = std::min(high, middle + offset);
86 if (adjacent == high) throw;
87 negative = assess(adjacent);
88 }
89 if (negative == 1) return result;
90 if (negative > 1)
91 low = result.shift;
92 else
93 high = result.shift;
94 }
95 throw std::runtime_error("No resolved index-one arc shift interval exists");
96}
TwistedRestrictedResult restrictedTraceDeterminant(const std::vector< Segment > &segments, const Matrix &twist, const Vector &unitNormal)
std::vector< gaussian::Segment > segments

◆ integrateConstrainedImaginaryTimePath()

template<class NativeEvaluate, class NativeEnergy>
ConstrainedImaginaryTimeTrajectory gpr::quantum::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 )
inline

Definition at line 218 of file ConstrainedImaginaryTimePath.h.

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}
@ y
Definition Enums.h:28

◆ jacobiArcToTurningContour()

JacobiPathEvaluation gpr::quantum::jacobiArcToTurningContour ( const std::vector< Eigen::VectorXd > & path,
const std::vector< PotentialEvaluation > & native,
double energy,
Eigen::VectorXd * turningPoint = nullptr )
inline

Definition at line 23 of file ThermalJacobiPeriod.h.

27{
28 if (path.size() < 3 || native.size() != path.size())
29 throw std::invalid_argument(
30 "Matching spatial arc nodes and energies required");
31 const auto last = path.size() - 1;
32 const double slope = native[last - 1].energy - native[last].energy;
33 if (!(slope > 0) || !(native[last - 1].energy > energy) ||
34 !std::isfinite(slope))
35 throw std::domain_error(
36 "A descending native outer turning chord is required");
37 auto q = path;
38 auto v = native;
39 const double fraction = (native[last - 1].energy - energy) / slope;
40 q.back() = path[last - 1] + fraction * (path[last] - path[last - 1]);
41 v.back().energy = energy;
42 if (turningPoint) *turningPoint = q.back();
43 return evaluateJacobiPath(q, v, energy);
44}

◆ jacobiSegment()

JacobiSegment gpr::quantum::jacobiSegment ( const Eigen::VectorXd & left,
const Eigen::VectorXd & right,
const PotentialEvaluation & vl,
const PotentialEvaluation & vr,
double energy )
inline

Definition at line 25 of file JacobiAction.h.

29{
30 const auto d = left.size();
31 if (d < 1 || right.size() != d || vl.gradient.size() != d ||
32 vr.gradient.size() != d || !left.allFinite() || !right.allFinite() ||
33 !vl.gradient.allFinite() || !vr.gradient.allFinite() ||
34 !std::isfinite(vl.energy) || !std::isfinite(vr.energy) ||
35 !std::isfinite(energy))
36 throw std::invalid_argument(
37 "Finite matching mass-coordinate Jacobi endpoints required");
38 const double a = vl.energy - energy, b = vr.energy - energy;
39 if (a < 0 || b < 0 || !std::isfinite(a) || !std::isfinite(b))
40 throw std::invalid_argument(
41 "Jacobi endpoints must lie in the classically forbidden region");
42 const Eigen::VectorXd delta = right - left;
43 const double length = delta.norm(), p = std::sqrt(a), q = std::sqrt(b),
44 scale = std::max(p, q);
45 if (!(length > 0) || !std::isfinite(length) || !(scale > 0))
46 throw std::invalid_argument(
47 "Nonzero Jacobi link and at least one positive endpoint potential "
48 "required");
49 const double x = p / scale, y = q / scale, sum = x + y,
50 c = std::sqrt(2.) / 3.;
51 const double integral = 2 * c * scale * (x * x + x * y + y * y) / sum;
52 const double da = c * (x + 2 * y) / (scale * sum * sum),
53 db = c * (2 * x + y) / (scale * sum * sum);
55 out.action = length * integral;
56 out.leftPotentialDerivative = length * da;
57 out.rightPotentialDerivative = length * db;
58 out.traversalTime = length * std::sqrt(2.) / (scale * sum);
59 out.leftGradient = -integral * (delta / length) +
60 out.leftPotentialDerivative * vl.gradient;
61 out.rightGradient = integral * (delta / length) +
62 out.rightPotentialDerivative * vr.gradient;
63 if (!std::isfinite(out.action) || !std::isfinite(out.traversalTime) ||
64 !out.leftGradient.allFinite() || !out.rightGradient.allFinite())
65 throw std::runtime_error(
66 "Nonfinite Jacobi action or endpoint derivative");
67 return out;
68}

◆ lineIntegralOrbit()

LineIntegralOrbit gpr::quantum::lineIntegralOrbit ( const LineIntegralNEBResult & result,
double energy,
std::size_t beads,
double hbar = 1.,
double boltzmann = 1.,
double tolerance = 1e-8 )
inline

Definition at line 769 of file LineIntegralNEB.h.

774{
775 if (!result.converged || beads < 4 || beads % 2 || !(hbar > 0) ||
776 !(boltzmann > 0) || !std::isfinite(hbar) || !std::isfinite(boltzmann) ||
777 !(tolerance > 0) || !std::isfinite(tolerance) ||
778 !std::isfinite(energy) || result.path.size() < 3 ||
779 result.native.size() != result.path.size())
780 throw std::invalid_argument(
781 "Qualified LI-NEB path, positive constants and even bead count "
782 "required");
783 auto values = result.native;
784 for (auto j: {std::size_t(0), values.size() - 1}) {
785 if (std::abs(values[j].energy - energy) > tolerance)
786 throw std::domain_error("LI-NEB turning energy is not qualified");
787 const auto neighbour = j == 0 ? std::size_t(1) : values.size() - 2;
788 if (result.path[j].size() < 1 ||
789 result.path[neighbour].size() != result.path[j].size() ||
790 values[j].gradient.size() != result.path[j].size() ||
791 !values[j].gradient.allFinite() || !result.path[j].allFinite() ||
792 !result.path[neighbour].allFinite())
793 throw std::invalid_argument(
794 "Finite matching LI-NEB turning coordinates and gradients "
795 "required");
796 if (!(values[j].gradient.dot(result.path[neighbour] - result.path[j]) >
797 0))
798 throw std::domain_error(
799 "LI-NEB turning orientation does not enter the forbidden "
800 "region");
801 values[j].energy = energy;
802 }
803 std::vector<double> cumulative{0.};
805 for (std::size_t j = 0; j + 1 < values.size(); ++j) {
806 const auto link = jacobiSegment(result.path[j], result.path[j + 1],
807 values[j], values[j + 1], energy);
808 cumulative.push_back(cumulative.back() + link.traversalTime);
809 out.abbreviatedAction += 2 * link.action;
810 }
811 out.period = 2 * cumulative.back();
812 out.temperature = hbar / (boltzmann * out.period);
813 out.euclideanAction = out.abbreviatedAction + energy * out.period;
814 for (std::size_t bead = 0; bead < beads; ++bead) {
815 const double t =
816 out.period * double(std::min(bead, beads - bead)) / double(beads);
817 std::size_t j =
818 std::upper_bound(cumulative.begin(), cumulative.end(), t) -
819 cumulative.begin() - 1;
820 j = std::min(j, values.size() - 2);
821 const double u = std::clamp(
822 (t - cumulative[j]) / (cumulative[j + 1] - cumulative[j]), 0., 1.);
823 const double a = std::sqrt(values[j].energy - energy),
824 b = std::sqrt(values[j + 1].energy - energy);
825 const double fraction = u * (2 * a + (b - a) * u) / (a + b);
826 out.ring.push_back((1 - fraction) * result.path[j] +
827 fraction * result.path[j + 1]);
828 }
829 return out;
830}
std::vector< Eigen::VectorXd > path
std::vector< PotentialEvaluation > native

◆ lineIntegralSearchForces()

std::vector< Eigen::VectorXd > gpr::quantum::lineIntegralSearchForces ( const std::vector< Eigen::VectorXd > & q,
const std::vector< PotentialEvaluation > & values,
const LineIntegralNEBState & state,
const LineIntegralNEBOptions & options )
inline

Definition at line 324 of file LineIntegralNEB.h.

328{
329 if (q.size() < 3 || values.size() != q.size() ||
330 state.force.size() != q.size())
331 throw std::invalid_argument(
332 "Matching LI-NEB search force nodes required");
333 const auto dimension = q.front().size();
334 for (std::size_t j = 0; j < q.size(); ++j)
335 if (dimension < 1 || q[j].size() != dimension ||
336 state.force[j].size() != dimension || !q[j].allFinite() ||
337 !state.force[j].allFinite() || !std::isfinite(values[j].energy))
338 throw std::invalid_argument(
339 "Finite matching LI-NEB search vectors required");
340 auto result = state.force;
341 if (!options.geometricPreconditioning) return result;
342 if (!(options.hbar > 0) || !std::isfinite(options.hbar) ||
343 !std::isfinite(options.energy))
344 throw std::invalid_argument(
345 "Finite positive LI-NEB search units required");
346 for (std::size_t j = 1; j + 1 < q.size(); ++j) {
347 const double length =
348 .5 * ((q[j] - q[j - 1]).norm() + (q[j + 1] - q[j]).norm());
349 const double scale =
350 options.hbar * std::sqrt(2 * (values[j].energy - options.energy)) /
351 length;
352 if (!(scale > 0) || !std::isfinite(scale))
353 throw std::domain_error(
354 "A resolved positive LI-NEB normal search scale is required");
355 const Eigen::VectorXd tangent =
356 detail::lineIntegralUnitTangent(q, values, j);
357 const Eigen::VectorXd parallel = tangent.dot(state.force[j]) * tangent;
358 result[j] = scale * (state.force[j] - parallel) + parallel;
359 if (!result[j].allFinite())
360 throw std::runtime_error(
361 "Nonfinite geometrically conditioned LI-NEB search force");
362 }
363 return result;
364}
std::vector< Eigen::VectorXd > force

◆ lineIntegralSIDPPSeed()

std::vector< Eigen::VectorXd > gpr::quantum::lineIntegralSIDPPSeed ( neb::NEBPath & physicalBand,
int atoms,
const std::vector< char > & moving,
const MassMetric & metric,
double alpha = .33 )
inline

Definition at line 897 of file GPLineIntegralNEB.h.

900{
901 physicalBand.initializeSIDPP(atoms, moving, alpha);
902 std::vector<Eigen::VectorXd> result;
903 for (int j = 0; j < physicalBand.numImages(); ++j)
904 result.push_back(metric.weighted(physicalBand.image(j).positions));
905 return result;
906}
int numImages() const
Definition NEBPath.h:338
void initializeSIDPP(int n_atoms, double alpha=0.33)
Initialize via Sequential IDPP (SIDPP). rgsaddle_sidpp_alternating_path. The spring on that call is t...
Definition NEBPath.cpp:712
Image & image(int i)
Access image i.
Definition NEBPath.h:329
Eigen::VectorXd weighted(const Eigen::VectorXd &x) const
Eigen::VectorXd positions
Definition NEBPath.h:40

◆ lineIntegralStringActionForces()

std::vector< Eigen::VectorXd > gpr::quantum::lineIntegralStringActionForces ( const std::vector< Eigen::VectorXd > & q,
const std::vector< PotentialEvaluation > & values,
double energy,
double hbar,
LineIntegralAction action )
inline

Definition at line 60 of file LineIntegralString.h.

64{
65 const std::size_t n = q.size();
66 std::vector<Eigen::VectorXd> force(n,
67 Eigen::VectorXd::Zero(q.front().size()));
69 auto contourValues = values;
70 contourValues.front().energy = energy;
71 contourValues.back().energy = energy;
72 const auto exact = evaluateJacobiPath(q, contourValues, energy);
73 for (std::size_t j = 1; j + 1 < n; ++j)
74 force[j] = -exact.gradient[j] / hbar;
75 return force;
76 }
77
78 std::vector<double> xi(n, 0.), length(n - 1);
79 for (std::size_t j = 1; j + 1 < n; ++j)
80 xi[j] = std::sqrt(2. * (values[j].energy - energy)) / hbar;
81 for (std::size_t j = 1; j < n; ++j)
82 length[j - 1] = (q[j] - q[j - 1]).norm();
83 for (std::size_t j = 1; j + 1 < n; ++j) {
84 const Eigen::VectorXd left = (q[j] - q[j - 1]) / length[j - 1];
85 const Eigen::VectorXd right = (q[j + 1] - q[j]) / length[j];
86 force[j] = -.5 * (length[j - 1] + length[j]) / (hbar * hbar * xi[j]) *
87 values[j].gradient -
88 .5 * (xi[j] + xi[j - 1]) * left +
89 .5 * (xi[j + 1] + xi[j]) * right;
90 }
91 return force;
92}

◆ lineIntegralStringNeedsReparameterization()

bool gpr::quantum::lineIntegralStringNeedsReparameterization ( const std::vector< Eigen::VectorXd > & path)
inline

Definition at line 145 of file LineIntegralString.h.

147{
148 if (path.size() < 3)
149 throw std::invalid_argument(
150 "A line-integral string requires at least three nodes");
151 double total = 0., largestDifference = 0., previous = 0.;
152 for (std::size_t j = 1; j < path.size(); ++j) {
153 if (path[j].size() != path.front().size() || !path[j].allFinite())
154 throw std::invalid_argument(
155 "Finite matching line-integral string coordinates required");
156 const double length = (path[j] - path[j - 1]).norm();
157 if (!(length > 0.) || !std::isfinite(length))
158 throw std::invalid_argument(
159 "Distinct adjacent line-integral string nodes required");
160 total += length;
161 if (!std::isfinite(total))
162 throw std::overflow_error("Line-integral string length overflowed");
163 if (j > 1)
164 largestDifference =
165 std::max(largestDifference, std::abs(length - previous));
166 previous = length;
167 }
168 return largestDifference > total / (10. * double(path.size() - 1));
169}

◆ logConstrainedQuantumBandWeight()

double gpr::quantum::logConstrainedQuantumBandWeight ( const std::vector< ConstrainedQuantumBandBranch > & branches,
double beta,
double hbar )
inline

Definition at line 142 of file ConstrainedQuantumProfile.h.

145{
146 if (branches.empty() || !(beta > 0.) || !std::isfinite(beta) ||
147 !(hbar > 0.) || !std::isfinite(hbar))
148 throw std::invalid_argument(
149 "Nonempty positive band branches and finite positive units "
150 "required");
151 const double period = beta * hbar;
152 if (!(period > 0.) || !std::isfinite(period))
153 throw std::invalid_argument(
154 "Resolved finite imaginary-time period required");
155 const auto dimension = constrained_quantum_band_detail::fullDimension(
156 branches.front().fluctuations);
157 const auto physical = branches.front().physicalCodimension;
158 std::vector<double> logarithms;
159 logarithms.reserve(branches.size());
160 for (const auto& branch: branches) {
161 constrained_quantum_band_detail::validateShape(branch);
162 const auto& fluctuations = branch.fluctuations;
163 if (constrained_quantum_band_detail::fullDimension(fluctuations) !=
164 dimension ||
165 branch.physicalCodimension != physical ||
166 !(fluctuations.duration > 0.) ||
167 !std::isfinite(fluctuations.duration) ||
168 std::abs(fluctuations.duration - period) >
169 128. * std::numeric_limits<double>::epsilon() *
170 std::max(fluctuations.duration, period))
171 throw std::invalid_argument(
172 "Band branches must share physical dimension, observable "
173 "codimension and imaginary-time period");
174 const double gaussian = fluctuations.logPositiveDensity(hbar);
175 const long double value =
176 -static_cast<long double>(branch.action) / hbar + gaussian +
177 std::log(branch.quadratureWeight) + branch.logCoareaJacobian;
178 const double logarithm = static_cast<double>(value);
179 if (!std::isfinite(logarithm))
180 throw std::overflow_error(
181 "Unrepresentable positive constrained-band logarithm");
182 logarithms.push_back(logarithm);
183 }
184 const double maximum =
185 *std::max_element(logarithms.begin(), logarithms.end());
186 long double sum = 0.;
187 for (const double value: logarithms)
188 sum += std::exp(static_cast<long double>(value) - maximum);
189 const double result = maximum + static_cast<double>(std::log(sum));
190 if (!std::isfinite(result))
191 throw std::overflow_error(
192 "Unrepresentable positive constrained-band sum");
193 return result;
194}

◆ logConstraintFamilyJacobian()

double gpr::quantum::logConstraintFamilyJacobian ( const Eigen::MatrixXd & normals,
const std::vector< Eigen::MatrixXd > & normalDerivatives,
const Eigen::MatrixXd & targetDerivatives,
const Eigen::VectorXd & point )

Log coarea for N(theta)^T q=c(theta), with jointly orthonormal columns. normalDerivatives[b] is partial_b N; targetDerivatives(a,b) is partial_b c_a. Singular charts must be excluded from quadrature rather than assigned a finite Gaussian density. Parameter units are handled by column scaling.

Definition at line 12 of file ConstrainedFamilyRate.cpp.

16{
17 const auto k = normals.cols(), d = normals.rows();
18 if (k < 1 || d < k || point.size() != d || targets.rows() != k ||
19 targets.cols() != k ||
20 derivatives.size() != static_cast<std::size_t>(k) ||
21 !normals.allFinite() || !targets.allFinite() || !point.allFinite() ||
22 (normals.transpose() * normals - Eigen::MatrixXd::Identity(k, k))
23 .norm() > 1e-12 * k)
24 throw std::invalid_argument(
25 "Finite matching orthonormal constraint chart required");
26 Eigen::MatrixXd jacobian(k, k);
27 double logScale = 0;
28 for (Eigen::Index b = 0; b < k; ++b) {
29 const auto& derivative = derivatives[b];
30 if (derivative.rows() != d || derivative.cols() != k ||
31 !derivative.allFinite() ||
32 (normals.transpose() * derivative +
33 derivative.transpose() * normals)
34 .stableNorm() >
35 1e-12 * std::max(1., derivative.stableNorm()))
36 throw std::invalid_argument(
37 "Constraint derivatives must be tangent to the orthonormal "
38 "frame");
39 jacobian.col(b) = targets.col(b) - derivative.transpose() * point;
40 const double scale = jacobian.col(b).stableNorm();
41 if (!(scale > 0) || !std::isfinite(scale))
42 throw std::domain_error(
43 "Constraint parameters define a singular or unrepresentable "
44 "chart");
45 jacobian.col(b) /= scale;
46 logScale += std::log(scale);
47 }
48 const Eigen::JacobiSVD<Eigen::MatrixXd> svd(jacobian);
49 const auto& singular = svd.singularValues();
50 if (svd.info() != Eigen::Success || !singular.allFinite() ||
51 singular.minCoeff() <= 128 * std::numeric_limits<double>::epsilon() *
52 k * singular.maxCoeff())
53 throw std::domain_error(
54 "Constraint parameters do not resolve an independent chart");
55 const double result = logScale + singular.array().log().sum();
56 if (!std::isfinite(result))
57 throw std::overflow_error("Unrepresentable coarea logarithm");
58 return result;
59}

◆ logImFConstrainedFamilyRate()

double gpr::quantum::logImFConstrainedFamilyRate ( double referenceAction,
const gaussian::TwistedTraceResult & reference,
const std::vector< ConstrainedFamilyPoint > & family,
Eigen::Index retainedCoordinates,
double hbar,
double symmetryFactor = 1 )

ImF integral retaining k soft coordinates explicitly. The restricted physical Gaussian has codimension k and exactly one negative direction. Its determinant retains all original kinetic link factors. Weights cover the supplied k-dimensional parameter domain; the coarea and normalization (2*pi*hbar)^(-k/2) replace the retained Gaussian integrations. Conditional stationarity, native curvatures and tail coverage are the caller's responsibility. No amplitude saddle approximation is applied.

Definition at line 61 of file ConstrainedFamilyRate.cpp.

65{
66 if (k < 1 || reference.dimension <= k || !std::isfinite(referenceAction) ||
67 !(hbar > 0) || !std::isfinite(hbar) || !(symmetryFactor > 0) ||
68 !std::isfinite(symmetryFactor) || family.empty() ||
69 !(reference.duration > 0) || !std::isfinite(reference.duration))
70 throw std::invalid_argument(
71 "Finite reference, retained coordinates and positive integration "
72 "scales required");
73 const double referenceLog = reference.logPositiveTrace();
74 std::vector<double> logarithms;
75 for (const auto& point: family) {
76 const auto& result = point.fluctuations;
77 if (!std::isfinite(point.action) || !(point.quadratureWeight > 0) ||
78 !std::isfinite(point.quadratureWeight) ||
79 !std::isfinite(point.logParameterJacobian) ||
80 result.codimension != k ||
81 result.dimension != reference.dimension - k ||
82 !std::isfinite(result.duration) ||
83 std::abs(result.duration - reference.duration) >
84 128 * std::numeric_limits<double>::epsilon() *
85 reference.duration)
86 throw std::invalid_argument(
87 "Conditional family must match reference measure and retained "
88 "dimension");
89 if (!result.logAbsNormalizedDet ||
90 !std::isfinite(*result.logAbsNormalizedDet) ||
91 result.inertia.negative != 1 || result.inertia.zero ||
92 result.unresolvedBorderEigenvalues ||
93 result.inertia.positive !=
94 static_cast<std::size_t>(result.dimension - 1))
95 throw std::domain_error(
96 "Conditional transverse Gaussian must have one resolved "
97 "negative mode");
98 const double value = std::log(point.quadratureWeight) +
99 point.logParameterJacobian +
100 (referenceAction - point.action) / hbar -
101 .5 * *result.logAbsNormalizedDet - referenceLog;
102 if (!std::isfinite(value))
103 throw std::overflow_error(
104 "Unrepresentable conditional family integrand");
105 logarithms.push_back(value);
106 }
107 const double maximum =
108 *std::max_element(logarithms.begin(), logarithms.end());
109 long double sum = 0;
110 for (const auto value: logarithms)
111 sum += std::exp(static_cast<long double>(value - maximum));
112 const double result = maximum + static_cast<double>(std::log(sum)) +
113 std::log(symmetryFactor) -
114 std::log(reference.duration) -
115 .5 * static_cast<double>(k) *
116 (std::log(2 * std::numbers::pi) + std::log(hbar));
117 if (!std::isfinite(result))
118 throw std::overflow_error("Unrepresentable conditional family rate");
119 return result;
120}

◆ logImFSaddleFamilyRate()

double gpr::quantum::logImFSaddleFamilyRate ( double referenceAction,
const gaussian::TwistedTraceResult & reference,
const std::vector< SaddleFamilyPoint > & family,
double hbar,
double symmetryFactor = 1 )

Logarithmic ImF rate of a supplied closed-path saddle family. Weights integrate the caller's phase coordinate over its explicitly covered domain. Each transverse Gaussian must have exactly one resolved negative direction and one removed phase coordinate. The matched reactant must be positive, with the same duration, energy zero, coordinate units and measure. The negative-contour half cancels the 2/duration ImF rate factor.

A conditional family, its coverage, Jacobians and physical Hessians are caller-supplied evidence. Stationarity, phase volume and degeneracies are not inferred. The result uses inverse units of the supplied duration.

Definition at line 31 of file SaddleFamilyRate.cpp.

35{
36 if (!std::isfinite(referenceAction) || !(hbar > 0) ||
37 !std::isfinite(hbar) || !(symmetryFactor > 0) ||
38 !std::isfinite(symmetryFactor) || family.empty() ||
39 reference.dimension < 2 || !(reference.duration > 0) ||
40 !std::isfinite(reference.duration))
41 throw std::invalid_argument(
42 "Finite matched reactant, phase quadrature and positive scales "
43 "required");
44 const double referenceLog = reference.logPositiveTrace();
45 std::vector<double> logarithms;
46 for (const auto& point: family) {
47 const auto& result = point.fluctuations;
48 if (!std::isfinite(point.action) || !(point.quadratureWeight > 0) ||
49 !std::isfinite(point.quadratureWeight) ||
50 !(point.phaseJacobian > 0) || !std::isfinite(point.phaseJacobian) ||
51 result.codimension != 1 ||
52 result.dimension != reference.dimension - 1 ||
53 !std::isfinite(result.duration) ||
54 std::abs(result.duration - reference.duration) >
55 128 * std::numeric_limits<double>::epsilon() *
56 reference.duration)
57 throw std::invalid_argument(
58 "Finite regular saddle-family points must match the reactant "
59 "measure");
60 if (!result.logAbsNormalizedDet ||
61 !std::isfinite(*result.logAbsNormalizedDet) ||
62 result.inertia.negative != 1 || result.inertia.zero ||
63 result.unresolvedBorderEigenvalues ||
64 result.inertia.positive !=
65 static_cast<std::size_t>(result.dimension - 1))
66 throw std::domain_error(
67 "Each transverse saddle Gaussian must have exactly one "
68 "resolved negative mode");
69 const double value = std::log(point.quadratureWeight) +
70 std::log(point.phaseJacobian) +
71 (referenceAction - point.action) / hbar -
72 .5 * *result.logAbsNormalizedDet - referenceLog;
73 if (!std::isfinite(value))
74 throw std::overflow_error(
75 "Unrepresentable saddle-family logarithm");
76 logarithms.push_back(value);
77 }
78 const double largest =
79 *std::max_element(logarithms.begin(), logarithms.end());
80 long double sum = 0;
81 for (double value: logarithms)
82 sum += std::exp(static_cast<long double>(value - largest));
83 const double result =
84 largest + static_cast<double>(std::log(sum)) +
85 std::log(symmetryFactor) - std::log(reference.duration) -
86 .5 * (std::log(2 * std::numbers::pi) + std::log(hbar));
87 if (!std::isfinite(result))
88 throw std::overflow_error(
89 "Unrepresentable saddle-family rate logarithm");
90 return result;
91}

◆ matchThermalJacobiPeriod()

ThermalJacobiPeriod gpr::quantum::matchThermalJacobiPeriod ( const Eigen::MatrixXd & well,
const std::vector< Eigen::VectorXd > & path,
const std::vector< PotentialEvaluation > & native,
double thermalPeriod,
double hbar )
inline

Definition at line 51 of file ThermalJacobiPeriod.h.

55{
56 if (path.size() < 3 || native.size() != path.size() ||
57 !(thermalPeriod > 0) || !std::isfinite(thermalPeriod) || !(hbar > 0) ||
58 !std::isfinite(hbar))
59 throw std::invalid_argument(
60 "Finite positive thermal scales and a matching spatial arc "
61 "required");
62 const HarmonicTurningTail tail(well);
63 const auto& cut = path.front();
64 if (cut.size() != well.rows() || !cut.allFinite())
65 throw std::invalid_argument("Harmonic cut and spatial metric differ");
66 const double cutEnergy = .5 * cut.dot(well * cut);
67 double bound = cutEnergy;
68 for (std::size_t j = 0; j + 1 < native.size(); ++j) {
69 if (!(native[j].energy > 0) || !std::isfinite(native[j].energy))
70 throw std::domain_error(
71 "The measured spatial arc must enter the forbidden region");
72 bound = std::min(bound, native[j].energy);
73 }
74 if (!(bound > 0) || !std::isfinite(bound))
75 throw std::domain_error(
76 "A positive harmonic matching energy is required");
77 const double minimumTime = tail.halfDurationForLogEnergy(
78 cut, std::log(bound) - std::log(2.), hbar);
79 const double maximumTime = .5 * thermalPeriod;
80 if (!(minimumTime < maximumTime))
81 throw std::domain_error(
82 "Thermal period is too short for this harmonic-cut branch");
83 auto evaluate = [&](double t) {
84 const auto harmonic = tail.evaluate(cut, t, hbar);
85 Eigen::VectorXd turning;
86 const auto arc =
87 jacobiArcToTurningContour(path, native, harmonic.energy, &turning);
88 ThermalJacobiPeriod out;
89 out.energy = harmonic.energy;
90 out.logEnergy = harmonic.logEnergy;
91 out.tailHalfDuration = t;
92 out.oneWayArcTime = arc.traversalTime;
93 out.period = 2 * (t + arc.traversalTime);
94 out.periodResidual = out.period - thermalPeriod;
95 out.abbreviatedAction = 2 * arc.action + harmonic.abbreviatedAction;
96 out.canonicalAction =
97 out.abbreviatedAction + thermalPeriod * harmonic.energy;
98 out.outerContourEnergyError =
99 std::abs(native.back().energy - harmonic.energy);
100 out.matchingEnergyError = std::abs(native.front().energy - cutEnergy);
101 out.tailMomentum = harmonic.momentum;
102 out.outerTurningPoint = turning;
103 const Eigen::VectorXd tangent = (path[1] - path.front()).normalized();
104 out.cutMomentumResidual =
105 (harmonic.momentum -
106 std::sqrt(2 * (native.front().energy - harmonic.energy)) * tangent)
107 .norm();
108 out.outerTurningDisplacement = (turning - path.back()).norm();
109 return out;
110 };
111 double right = maximumTime, left = minimumTime;
112 (void)evaluate(right);
113 bool bracketed = false;
114 for (unsigned j = 1; j <= 128; ++j) {
115 const double candidate =
116 maximumTime - (maximumTime - minimumTime) * (double(j) / 128.);
117 const auto lower = evaluate(candidate);
118 if (lower.periodResidual <= 0) {
119 left = candidate;
120 bracketed = true;
121 break;
122 }
123 right = candidate;
124 }
125 if (!bracketed)
126 throw std::domain_error(
127 "No tail-dominated thermal period bracket on this spatial arc");
128 for (unsigned iteration = 0; iteration < 100; ++iteration) {
129 const double t = .5 * (left + right);
130 auto state = evaluate(t);
131 if (std::abs(state.periodResidual) <= 2e-13 * thermalPeriod)
132 return state;
133 if (state.periodResidual > 0)
134 right = t;
135 else
136 left = t;
137 }
138 throw std::runtime_error(
139 "Thermal spatial period matching does not converge");
140}
JacobiPathEvaluation jacobiArcToTurningContour(const std::vector< Eigen::VectorXd > &path, const std::vector< PotentialEvaluation > &native, double energy, Eigen::VectorXd *turningPoint=nullptr)

◆ molecularBlockFluctuations()

MolecularBlockFluctuations gpr::quantum::molecularBlockFluctuations ( const std::vector< Eigen::VectorXd > & positions,
const Eigen::VectorXd & masses,
const std::vector< Eigen::MatrixXd > & physicalHessians,
double beta,
double hbar = 1 )
inline

Definition at line 20 of file MolecularBlockRate.h.

25{
26 using V = Eigen::VectorXd;
27 using M = Eigen::MatrixXd;
28 const std::size_t n = positions.size();
29 const Eigen::Index d = masses.size(), nd = n * d;
30 if (n < 4 || n % 2 || d < 9 || d % 3 || physicalHessians.size() != n ||
31 !(beta > 0) || !std::isfinite(beta) || !(hbar > 0) ||
32 !std::isfinite(hbar) || !masses.allFinite() ||
33 !(masses.array() > 0).all())
34 throw std::invalid_argument(
35 "Matching molecular block ring and positive finite units required");
36 const double h = beta * hbar / n;
37 if (!(h > 0) || !std::isfinite(h))
38 throw std::invalid_argument(
39 "Resolved positive molecular link duration required");
40 const V roots = masses.array().sqrt(), inverse = roots.cwiseInverse();
41 V stacked(nd), stackMass(nd), phase(nd);
42 std::vector<M> curvatures;
43 double bn = 0;
44 for (std::size_t j = 0; j < n; ++j) {
45 if (positions[j].size() != d || !positions[j].allFinite() ||
46 physicalHessians[j].rows() != d ||
47 physicalHessians[j].cols() != d || !physicalHessians[j].allFinite())
48 throw std::invalid_argument(
49 "Finite matching molecular block nodes required");
50 if ((physicalHessians[j] - physicalHessians[j].transpose()).norm() >
51 1e-8 * std::max(1., physicalHessians[j].norm()))
52 throw std::invalid_argument(
53 "Symmetric physical block Hessians required");
54 stacked.segment(j * d, d) = positions[j];
55 stackMass.segment(j * d, d) = masses;
56 curvatures.push_back(inverse.asDiagonal() * physicalHessians[j] *
57 inverse.asDiagonal());
58 }
59 for (std::size_t j = 0; j < n; ++j) {
60 const auto next = (j + 1) % n, previous = (j + n - 1) % n;
61 phase.segment(j * d, d) =
62 roots.cwiseProduct(positions[next] - positions[previous]);
63 bn += roots.cwiseProduct(positions[next] - positions[j]).squaredNorm();
64 }
65 const M rigid = molecularRigidModes(stacked, stackMass);
66 if (rigid.cols() != 6 || !(bn > 0) || !std::isfinite(bn))
67 throw std::domain_error(
68 "Noncollapsed nonlinear molecular block ring required");
69 for (int repeat = 0; repeat < 2; ++repeat)
70 phase -= rigid * (rigid.transpose() * phase);
71 if (!(phase.norm() > 0))
72 throw std::domain_error(
73 "Resolved molecular block time tangent required");
74 phase.normalize();
75 M normals(nd, 7);
76 normals.leftCols(6) = rigid;
77 normals.col(6) = phase;
78 std::vector<gaussian::Segment> links;
79 V response(nd);
80 for (std::size_t j = 0; j < n; ++j) {
81 const auto next = (j + 1) % n, previous = (j + n - 1) % n;
82 gaussian::Segment link;
83 link.A = M::Identity(d, d) / h + .5 * h * curvatures[j];
84 link.rightA = M::Identity(d, d) / h + .5 * h * curvatures[next];
85 link.L = M::Identity(d, d) / h;
86 link.duration = h;
87 link.logDetL = -d * std::log(h);
88 links.push_back(std::move(link));
89 response.segment(j * d, d) =
90 curvatures[j] * phase.segment(j * d, d) +
91 (2 * phase.segment(j * d, d) - phase.segment(previous * d, d) -
92 phase.segment(next * d, d)) /
93 (h * h);
94 }
96 result.determinant =
97 gaussian::restrictedTraceDeterminant(links, M::Identity(d, d), normals);
98 if (!result.determinant.logAbsNormalizedDet ||
99 result.determinant.inertia.negative != 1 ||
100 result.determinant.inertia.zero || result.determinant.codimension != 7)
101 throw std::domain_error(
102 "Resolved one-index molecular block determinant required");
103 result.logVibrationalPartition =
104 -.5 * (*result.determinant.logAbsNormalizedDet) + 3.5 * std::log(h) +
105 7 * std::log(double(n)) +
106 .5 * std::log(2 * std::numbers::pi * bn * n / (beta * hbar * hbar));
107 result.logRotationalInertiaDeterminant =
108 molecularLogInertiaDeterminant(stacked, stackMass, double(n));
109 result.linkMassDisplacement = bn;
110 result.phaseRayleigh = phase.dot(response);
111 result.phaseEquationResidual = response.norm();
112 return result;
113}
Matrix molecularRigidModes(const Vector &x, const Vector &masses)
double molecularLogInertiaDeterminant(const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double copies=1)
gaussian::TwistedRestrictedResult determinant

◆ molecularBlockLogTunnelingFactor()

double gpr::quantum::molecularBlockLogTunnelingFactor ( const MolecularBlockFluctuations & ring,
const Eigen::VectorXd & saddleCurvatures,
double saddleLogInertia,
double actionRelativeToSaddleOverHbar,
double beta,
double hbar = 1 )
inline

Definition at line 114 of file MolecularBlockRate.h.

118{
119 if (!std::isfinite(saddleLogInertia) ||
120 !std::isfinite(actionRelativeToSaddleOverHbar))
121 throw std::invalid_argument(
122 "Finite matched molecular TST reference required");
123 return .5 * (ring.logRotationalInertiaDeterminant - saddleLogInertia) +
125 molecularLogTstVibrationalPartition(saddleCurvatures, beta, hbar) -
126 actionRelativeToSaddleOverHbar;
127}
double molecularLogTstVibrationalPartition(const Eigen::VectorXd &eigenvalues, double beta, double hbar=1)

◆ molecularBlockLogUnimolecularRate()

double gpr::quantum::molecularBlockLogUnimolecularRate ( const MolecularBlockFluctuations & ring,
const Eigen::VectorXd & reactantCurvatures,
double reactantLogInertia,
double actionRelativeToReactantOverHbar,
std::size_t nodes,
double beta,
double hbar = 1,
double symmetryFactor = 1 )
inline

Definition at line 128 of file MolecularBlockRate.h.

133{
134 if (nodes < 4 || ring.determinant.inertia.negative != 1 ||
135 ring.determinant.inertia.zero || ring.determinant.codimension != 7 ||
136 ring.determinant.dimension !=
137 static_cast<Eigen::Index>(nodes * (reactantCurvatures.size() + 6) -
138 7) ||
139 !std::isfinite(reactantLogInertia) ||
140 !std::isfinite(actionRelativeToReactantOverHbar) ||
141 !(symmetryFactor > 0) || !std::isfinite(symmetryFactor))
142 throw std::invalid_argument(
143 "Matched molecular block reactant and channel required");
144 return std::log(symmetryFactor) -
145 std::log(2 * std::numbers::pi * beta * hbar) +
146 .5 * (ring.logRotationalInertiaDeterminant - reactantLogInertia) +
148 molecularLogHarmonicRingPartition(reactantCurvatures, nodes, beta,
149 hbar) -
150 actionRelativeToReactantOverHbar;
151}
double molecularLogHarmonicRingPartition(const Eigen::VectorXd &curvatures, std::size_t nodes, double beta, double hbar=1)

◆ molecularInternalBasis()

Matrix gpr::quantum::molecularInternalBasis ( const Vector & x,
const Vector & masses )
inline

Definition at line 59 of file MolecularGeometry.h.

60{
61 const Matrix rigid = molecularRigidModes(x, masses);
62 Eigen::HouseholderQR<Matrix> qr(rigid);
63 const Matrix q = qr.householderQ() * Matrix::Identity(x.size(), x.size());
64 return q.rightCols(x.size() - rigid.cols());
65}
Eigen::MatrixXd Matrix

◆ molecularLogHarmonicRingPartition()

double gpr::quantum::molecularLogHarmonicRingPartition ( const Eigen::VectorXd & curvatures,
std::size_t nodes,
double beta,
double hbar = 1 )
inline

Definition at line 169 of file MolecularRingRate.h.

172{
173 if (nodes < 4 || curvatures.size() == 0 || !curvatures.allFinite() ||
174 !(curvatures.array() > 0).all() || !(beta > 0) ||
175 !std::isfinite(beta) || !(hbar > 0) || !std::isfinite(hbar))
176 throw std::invalid_argument(
177 "Positive molecular reactant curvature and finite ring units "
178 "required");
179 double value = 0;
180 for (double curvature: curvatures) {
181 const double x = nodes * std::asinh(beta * hbar * std::sqrt(curvature) /
182 (2 * nodes));
183 value -= x + std::log(-std::expm1(-2 * x));
184 }
185 return value;
186}

◆ molecularLogInertiaDeterminant()

double gpr::quantum::molecularLogInertiaDeterminant ( const Eigen::VectorXd & positions,
const Eigen::VectorXd & masses,
double copies = 1 )
inline

Definition at line 20 of file MolecularRingRate.h.

23{
24 if (positions.size() != masses.size() || positions.size() % 3 ||
25 !(copies > 0) || !positions.allFinite() || !masses.allFinite() ||
26 !(masses.array() > 0).all())
27 throw std::invalid_argument("Finite molecular inertia inputs required");
28 Eigen::Vector3d center = Eigen::Vector3d::Zero();
29 double total = 0;
30 for (Eigen::Index a = 0; a < positions.size() / 3; ++a) {
31 center += masses[3 * a] * positions.segment<3>(3 * a);
32 total += masses[3 * a];
33 }
34 center /= total;
35 Eigen::Matrix3d inertia = Eigen::Matrix3d::Zero();
36 for (Eigen::Index a = 0; a < positions.size() / 3; ++a) {
37 const Eigen::Vector3d r = positions.segment<3>(3 * a) - center;
38 inertia +=
39 (masses[3 * a] / copies) *
40 (r.squaredNorm() * Eigen::Matrix3d::Identity() - r * r.transpose());
41 }
42 Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eig(inertia);
43 if (eig.info() != Eigen::Success || !(eig.eigenvalues().array() > 0).all())
44 throw std::domain_error(
45 "Nonlinear molecular rotational inertia required");
46 return eig.eigenvalues().array().log().sum();
47}

◆ molecularLogTstVibrationalPartition()

double gpr::quantum::molecularLogTstVibrationalPartition ( const Eigen::VectorXd & eigenvalues,
double beta,
double hbar = 1 )
inline

Definition at line 148 of file MolecularRingRate.h.

150{
151 if (eigenvalues.size() < 2 || !eigenvalues.allFinite() ||
152 (eigenvalues.array() < 0).count() != 1 || !(beta > 0) ||
153 !std::isfinite(beta) || !(hbar > 0) || !std::isfinite(hbar))
154 throw std::invalid_argument(
155 "Index-one molecular TST eigenvalues and finite positive units "
156 "required");
157 double value = 0;
158 for (double curvature: eigenvalues)
159 if (curvature >= 0) {
160 if (!(curvature > 0))
161 throw std::domain_error("Unresolved molecular TST vibration");
162 const double x = .5 * beta * hbar * std::sqrt(curvature);
163 value -= x + std::log(-std::expm1(-2 * x));
164 }
165 return value;
166}

◆ molecularLogTunnelingFactor()

double gpr::quantum::molecularLogTunnelingFactor ( const MolecularRingFluctuations & ring,
const Eigen::VectorXd & saddleInternalEigenvalues,
double saddleLogInertiaDeterminant,
double actionRelativeToSaddleOverHbar,
double beta,
double hbar = 1 )
inline

Definition at line 218 of file MolecularRingRate.h.

223{
224 if (saddleInternalEigenvalues.size() < 2 ||
225 !saddleInternalEigenvalues.allFinite() ||
226 (saddleInternalEigenvalues.array() < 0).count() != 1 ||
227 !std::isfinite(saddleLogInertiaDeterminant) ||
228 !std::isfinite(actionRelativeToSaddleOverHbar) || !(beta > 0) ||
229 !(hbar > 0))
230 throw std::invalid_argument(
231 "Matched index-one molecular TST reference required");
232 const double logTst = molecularLogTstVibrationalPartition(
233 saddleInternalEigenvalues, beta, hbar);
234 return .5 * (ring.logRotationalInertiaDeterminant -
235 saddleLogInertiaDeterminant) +
236 ring.logVibrationalPartition - logTst -
237 actionRelativeToSaddleOverHbar;
238}

◆ molecularLogUnimolecularRate()

double gpr::quantum::molecularLogUnimolecularRate ( const MolecularRingFluctuations & ring,
const Eigen::VectorXd & reactantInternalCurvatures,
double reactantLogInertiaDeterminant,
double actionRelativeToReactantOverHbar,
std::size_t nodes,
double beta,
double hbar = 1,
double symmetryFactor = 1 )
inline

Definition at line 190 of file MolecularRingRate.h.

196{
197 if (nodes < 4 || ring.negativeModes != 1 || ring.rigidModes != 6 ||
198 ring.eigenvalues.size() !=
199 static_cast<Eigen::Index>(
200 nodes * (reactantInternalCurvatures.size() + 6) - 6) ||
201 !std::isfinite(reactantLogInertiaDeterminant) ||
202 !std::isfinite(actionRelativeToReactantOverHbar) ||
203 !(symmetryFactor > 0) || !std::isfinite(symmetryFactor))
204 throw std::invalid_argument(
205 "Matched nonlinear molecular ring, reactant and symmetry "
206 "convention required");
207 const double logReactant = molecularLogHarmonicRingPartition(
208 reactantInternalCurvatures, nodes, beta, hbar);
209 return std::log(symmetryFactor) -
210 std::log(2 * std::numbers::pi * beta * hbar) +
212 reactantLogInertiaDeterminant) +
213 ring.logVibrationalPartition - logReactant -
214 actionRelativeToReactantOverHbar;
215}

◆ molecularRigidModes()

Matrix gpr::quantum::molecularRigidModes ( const Vector & x,
const Vector & masses )
inline

Definition at line 18 of file MolecularGeometry.h.

19{
20 if (x.size() != masses.size() || x.size() % 3 || !x.allFinite() ||
21 !masses.allFinite() || !(masses.array() > 0).all())
22 throw std::invalid_argument(
23 "Finite molecular positions and positive Cartesian masses "
24 "required");
25 const auto atoms = x.size() / 3;
26 double total = 0;
27 Eigen::Vector3d center = Eigen::Vector3d::Zero();
28 for (Eigen::Index a = 0; a < atoms; ++a) {
29 if (masses[3 * a] != masses[3 * a + 1] ||
30 masses[3 * a] != masses[3 * a + 2])
31 throw std::invalid_argument(
32 "One isotropic mass per molecular atom required");
33 total += masses[3 * a];
34 center += masses[3 * a] * x.segment<3>(3 * a);
35 }
36 center /= total;
37 Matrix candidates = Matrix::Zero(x.size(), 6);
38 for (Eigen::Index a = 0; a < atoms; ++a)
39 for (int k = 0; k < 3; ++k) {
40 const double root = std::sqrt(masses[3 * a]);
41 candidates(3 * a + k, k) = root;
42 candidates.block<3, 1>(3 * a, 3 + k) =
43 root * Eigen::Vector3d::Unit(k).cross(
44 Eigen::Vector3d(x.segment<3>(3 * a) - center));
45 }
46 Matrix rigid(x.size(), 6);
47 Eigen::Index rank = 0;
48 for (int k = 0; k < 6; ++k) {
49 Vector v = candidates.col(k);
50 const double original = v.norm();
51 for (int repeat = 0; repeat < 2; ++repeat)
52 for (Eigen::Index j = 0; j < rank; ++j)
53 v -= rigid.col(j).dot(v) * rigid.col(j);
54 if (v.norm() > 1e-10 * std::max(1., original))
55 rigid.col(rank++) = v.normalized();
56 }
57 return rigid.leftCols(rank);
58}
Eigen::VectorXd Vector

◆ molecularRingFluctuations()

MolecularRingFluctuations gpr::quantum::molecularRingFluctuations ( const std::vector< Eigen::VectorXd > & positions,
const Eigen::VectorXd & masses,
const std::vector< Eigen::MatrixXd > & physicalHessians,
double beta,
double hbar = 1 )
inline

Definition at line 53 of file MolecularRingRate.h.

58{
59 using V = Eigen::VectorXd;
60 using M = Eigen::MatrixXd;
61 const auto n = positions.size();
62 const Eigen::Index d = masses.size(), nd = n * d;
63 if (n < 4 || n % 2 || physicalHessians.size() != n || d < 9 || d % 3 ||
64 !(beta > 0) || !std::isfinite(beta) || !(hbar > 0) ||
65 !std::isfinite(hbar) || !masses.allFinite() ||
66 !(masses.array() > 0).all())
67 throw std::invalid_argument(
68 "Even molecular ring, physical Hessians and finite positive units "
69 "required");
70 const double betaN = beta / n, spring = 1 / std::pow(betaN * hbar, 2);
71 const V roots = masses.array().sqrt();
72 const V inverse = roots.cwiseInverse();
73 M h = M::Zero(nd, nd);
74 V stacked(nd), stackMass(nd), phase(nd);
75 double bn = 0;
76 for (std::size_t j = 0; j < n; ++j) {
77 if (positions[j].size() != d || !positions[j].allFinite() ||
78 physicalHessians[j].rows() != d ||
79 physicalHessians[j].cols() != d || !physicalHessians[j].allFinite())
80 throw std::invalid_argument(
81 "Matching finite molecular ring nodes required");
82 if ((physicalHessians[j] - physicalHessians[j].transpose()).norm() >
83 1e-8 * std::max(1., physicalHessians[j].norm()))
84 throw std::invalid_argument(
85 "Symmetric physical ring Hessians required");
86 }
87 for (std::size_t j = 0; j < n; ++j) {
88 const auto next = (j + 1) % n, previous = (j + n - 1) % n;
89 h.block(j * d, j * d, d, d) =
90 inverse.asDiagonal() * physicalHessians[j] * inverse.asDiagonal() +
91 2 * spring * M::Identity(d, d);
92 h.block(j * d, next * d, d, d) -= spring * M::Identity(d, d);
93 h.block(next * d, j * d, d, d) -= spring * M::Identity(d, d);
94 stacked.segment(j * d, d) = positions[j];
95 stackMass.segment(j * d, d) = masses;
96 phase.segment(j * d, d) =
97 roots.cwiseProduct(positions[next] - positions[previous]);
98 bn += roots.cwiseProduct(positions[next] - positions[j]).squaredNorm();
99 }
100 const M internal = molecularInternalBasis(stacked, stackMass);
101 const auto rigid = nd - internal.cols();
102 if (rigid != 6 || !(bn > 0) || !std::isfinite(bn))
103 throw std::domain_error(
104 "Noncollapsed nonlinear molecular ring required");
105 V tangent = internal.transpose() * phase;
106 if (!(tangent.norm() > 0))
107 throw std::domain_error("Resolved molecular phase tangent required");
108 tangent.normalize();
109 Eigen::SelfAdjointEigenSolver<M> eig(
110 M(internal.transpose() * h * internal));
111 if (eig.info() != Eigen::Success)
112 throw std::runtime_error(
113 "Molecular ring fluctuation eigensolve failed");
114 MolecularRingFluctuations result;
115 result.eigenvalues = eig.eigenvalues();
116 result.rigidModes = rigid;
117 result.linkMassDisplacement = bn;
118 const V overlaps = (eig.eigenvectors().transpose() * tangent).cwiseAbs();
119 Eigen::Index phaseIndex;
120 result.phaseOverlap = overlaps.maxCoeff(&phaseIndex);
121 result.phaseIndex = phaseIndex;
122 result.phaseEigenvalue = eig.eigenvalues()[phaseIndex];
123 if (result.phaseOverlap < .9)
124 throw std::domain_error("No isolated molecular time-translation mode");
125 double closest = std::numeric_limits<double>::infinity(), logPartition = 0;
126 for (Eigen::Index k = 0; k < eig.eigenvalues().size(); ++k)
127 if (k != phaseIndex) {
128 const double value = eig.eigenvalues()[k];
129 if (std::abs(value) < 1e-14)
130 throw std::domain_error(
131 "Unresolved nonphase molecular fluctuation");
132 closest = std::min(closest, std::abs(value));
133 if (value < 0) ++result.negativeModes;
134 logPartition -= std::log(betaN * hbar * std::sqrt(std::abs(value)));
135 }
136 if (result.negativeModes != 1)
137 throw std::domain_error(
138 "Molecular instanton must have exactly one nonphase negative "
139 "direction");
140 result.phaseRelativeCurvature = std::abs(result.phaseEigenvalue) / closest;
141 result.logVibrationalPartition =
142 logPartition + (rigid + 1) * std::log(double(n)) +
143 .5 * std::log(2 * std::numbers::pi * bn * n / (beta * hbar * hbar));
144 result.logRotationalInertiaDeterminant =
145 molecularLogInertiaDeterminant(stacked, stackMass, double(n));
146 return result;
147}
Matrix molecularInternalBasis(const Vector &x, const Vector &masses)

◆ optimizeArcTail() [1/2]

ArcTailSearchResult gpr::quantum::optimizeArcTail ( const ArcTailAction & action,
const std::vector< Eigen::VectorXd > & initial,
double initialArcDuration,
const PathConstraints & constraints,
const ArcTailPotential & potential,
const ArcTailSearchOptions & options = {},
const std::function< void(const ArcTailSearchResult &)> & retain = {} )

◆ optimizeArcTail() [2/2]

ArcTailSearchResult gpr::quantum::optimizeArcTail ( const ArcTailAction & action,
const std::vector< V > & initial,
double duration,
const PathConstraints & constraints,
const ArcTailPotential & potential,
const ArcTailSearchOptions & options,
const std::function< void(const ArcTailSearchResult &)> & retain )

Definition at line 14 of file ArcTailOptimizer.cpp.

19{
20 auto require = [](bool value, const char* text) {
21 if (!value) throw std::invalid_argument(text);
22 };
23 const double period = action.period();
24 const auto& weights = action.arcWeights();
25 const auto n = initial.size();
26 const auto k = constraints.target.size();
27 require(
28 n >= 2 && weights.size() + 1 == n && constraints.normals.size() == n &&
29 k > 0 && constraints.target.allFinite() &&
30 bool(potential.evaluate) && bool(potential.searchHessians),
31 "Arc search requires nodes, weights, affine constraints and callbacks");
32 const auto d = initial.front().size();
33 require(d > 0, "Arc search requires a nonempty mass metric");
34 require(period > 0 && duration > 0 && duration < period &&
35 std::isfinite(period) && std::isfinite(duration) &&
36 options.forceTolerance > 0 &&
37 std::isfinite(options.forceTolerance) &&
38 options.energyTolerance > 0 &&
39 std::isfinite(options.energyTolerance) &&
40 options.constraintTolerance > 0 &&
41 std::isfinite(options.constraintTolerance) &&
42 options.maximumStep > 0 && std::isfinite(options.maximumStep) &&
43 options.maximumDurationFraction > 0 &&
44 options.maximumDurationFraction < 1 &&
45 options.maximumBacktracks > 0,
46 "Positive finite arc search scales required");
47 M gram = M::Zero(k, k);
48 double sum = 0;
49 for (std::size_t j = 0; j < n; ++j) {
50 require(initial[j].size() == d && initial[j].allFinite() &&
51 constraints.normals[j].rows() == d &&
52 constraints.normals[j].cols() == k &&
53 constraints.normals[j].allFinite(),
54 "Arc search metric or normal dimensions differ");
55 gram += constraints.normals[j].transpose() * constraints.normals[j];
56 }
57 for (double w: weights) {
58 require(w > 0 && std::isfinite(w),
59 "Positive finite arc time weights required");
60 sum += w;
61 }
62 require(
63 std::abs(sum - 1) < 1e-12 && (gram - M::Identity(k, k)).norm() < 1e-10,
64 "Normalized arc weights and orthonormal constraints required");
65 auto coordinate = [&](const std::vector<V>& points) {
66 V value = V::Zero(k);
67 for (std::size_t j = 0; j < n; ++j)
68 value += constraints.normals[j].transpose() * points[j];
69 return value;
70 };
71 auto enforce = [&](std::vector<V>& points) {
72 const V correction = constraints.target - coordinate(points);
73 for (std::size_t j = 0; j < n; ++j)
74 points[j] += constraints.normals[j] * correction;
75 };
76 std::size_t evaluations = 0, batches = 0, hessians = 0, physicalActions = 0;
77 auto ownedEvaluate = [&](const std::vector<V>& q) {
78 auto values = potential.evaluate(q);
79 ++batches;
80 evaluations += q.size();
81 return values;
82 };
83 auto measure = [&](const std::vector<V>& points, double u) {
85 result.path = points;
86 result.arcDuration = u;
87 result.native = ownedEvaluate(points);
88 result.forceGradient =
89 prepareArcTailForceGradient(action, points, u, result.native,
90 potential, options, ownedEvaluate);
91 physicalActions += result.forceGradient.physicalHessianActionRequests;
92 result.evaluation = evaluateArcTailForceGradient(
93 action, points, result.native, u, result.forceGradient);
94 V normal = V::Zero(k);
95 for (std::size_t j = 0; j < n; ++j)
96 normal += constraints.normals[j].transpose() *
97 result.evaluation.gradient[j];
98 for (std::size_t j = 0; j < n; ++j) {
99 const double time =
100 u * .5 *
101 ((j ? weights[j - 1] : 0) + (j + 1 < n ? weights[j] : 0));
102 result.fullForce = std::max(
103 result.fullForce, result.evaluation.gradient[j].norm() / time);
104 result.conditionalForce = std::max(result.conditionalForce,
105 (result.evaluation.gradient[j] -
106 constraints.normals[j] * normal)
107 .norm() /
108 time);
109 }
110 result.energyResidual = std::abs(result.evaluation.durationGradient);
111 result.constraintResidual =
112 (coordinate(points) - constraints.target).norm();
113 result.conditionalStationarityQualified =
114 result.conditionalForce <= options.forceTolerance &&
115 result.energyResidual <= options.energyTolerance &&
116 result.constraintResidual <= options.constraintTolerance;
117 result.fullStationarityQualified =
118 result.conditionalStationarityQualified &&
119 result.fullForce <= options.forceTolerance;
120 result.converged = options.requireFullStationarity
121 ? result.fullStationarityQualified
122 : result.conditionalStationarityQualified;
123 result.evaluations = evaluations;
124 result.batchEvaluations = batches;
125 result.searchHessianEvaluations = hessians;
126 result.physicalHessianActionEvaluations = physicalActions;
127 return result;
128 };
129 auto merit = [&](const ArcTailSearchResult& result,
130 double referenceDuration) {
131 const double force = options.requireFullStationarity
132 ? result.fullForce
133 : result.conditionalForce;
134 return std::hypot(
135 std::hypot(force * result.arcDuration /
136 (referenceDuration * options.forceTolerance),
137 result.energyResidual / options.energyTolerance),
138 result.constraintResidual / options.constraintTolerance);
139 };
140 auto points = initial;
141 enforce(points);
142 auto state = measure(points, duration);
143 if (retain) retain(state);
144 for (std::size_t iteration = 0;
145 !state.converged && iteration < options.maximumIterations;
146 ++iteration) {
147 const auto curvature = potential.searchHessians(state.path);
148 hessians += state.path.size();
149 std::vector<M> thirdContractions;
150 if (state.forceGradient.enabled) {
151 require(options.physicalHessianStep > 0 &&
152 std::isfinite(options.physicalHessianStep),
153 "A finite positive search derivative step is required");
154 const double epsilon = options.physicalHessianStep;
155 thirdContractions.assign(n, M::Zero(d, d));
156 std::vector<std::size_t> active;
157 std::vector<double> norms(n, 0.);
158 std::vector<V> probes;
159 probes.reserve(2 * n);
160 for (std::size_t j = 0; j < n; ++j) {
161 norms[j] = state.forceGradient.residualGradients[j].norm();
162 require(std::isfinite(norms[j]),
163 "Finite residual-gradient norms required");
164 if (norms[j] == 0) continue;
165 const V displacement =
166 epsilon * state.forceGradient.residualGradients[j] /
167 norms[j];
168 active.push_back(j);
169 probes.push_back(state.path[j] + displacement);
170 probes.push_back(state.path[j] - displacement);
171 }
172 if (!probes.empty()) {
173 const auto measured = potential.searchHessians(probes);
174 hessians += probes.size();
175 require(measured.size() == probes.size(),
176 "Search Hessian probe batch shape differs");
177 for (const auto& value: measured)
178 require(value.rows() == d && value.cols() == d &&
179 value.allFinite() &&
180 (value - value.transpose()).norm() <=
181 1e-12 * std::max(1., value.norm()),
182 "Finite symmetric search Hessian probes required");
183 for (std::size_t slot = 0; slot < active.size(); ++slot) {
184 const auto j = active[slot];
185 const M response =
186 norms[j] *
187 (measured[2 * slot] - measured[2 * slot + 1]) /
188 (2 * epsilon);
189 thirdContractions[j] =
190 .5 * (response + response.transpose());
191 require(thirdContractions[j].allFinite(),
192 "Finite search third contraction required");
193 }
194 }
195 }
196 const auto quadratic = evaluateArcTailForceGradient(
197 action, state.path, state.native, state.arcDuration,
198 state.forceGradient, curvature, thirdContractions);
200 try {
201 step =
202 solveArcTailNewton(quadratic, constraints.normals,
203 constraints.target - coordinate(state.path));
204 } catch (const std::exception& error) {
205 state.failure = error.what();
206 break;
207 }
208 double maximum = 0;
209 for (const auto& value: step.displacement)
210 maximum = std::max(maximum, value.norm());
211 double scale =
212 maximum > options.maximumStep ? options.maximumStep / maximum : 1.;
213 if (step.durationDisplacement != 0)
214 scale = std::min(scale, options.maximumDurationFraction *
215 std::min(state.arcDuration,
216 period - state.arcDuration) /
217 std::abs(step.durationDisplacement));
218 bool accepted = false;
219 for (std::size_t trial = 0; trial < options.maximumBacktracks;
220 ++trial, scale *= .5) {
221 auto candidate = state.path;
222 for (std::size_t j = 0; j < n; ++j)
223 candidate[j] += scale * step.displacement[j];
224 enforce(candidate);
225 auto next =
226 measure(candidate,
227 state.arcDuration + scale * step.durationDisplacement);
228 if (merit(next, state.arcDuration) <
229 merit(state, state.arcDuration)) {
230 next.acceptedSteps = state.acceptedSteps + 1;
231 state = std::move(next);
232 accepted = true;
233 if (retain) retain(state);
234 break;
235 }
236 }
237 if (!accepted) {
238 state.failure =
239 "Arc-tail native residual does not decrease along the joint "
240 "step";
241 break;
242 }
243 }
244 if (!state.converged && state.failure.empty())
245 state.failure = "Maximum arc-tail iterations reached";
246 state.evaluations = evaluations;
247 state.batchEvaluations = batches;
248 state.searchHessianEvaluations = hessians;
249 state.physicalHessianActionEvaluations = physicalActions;
250 return state;
251}
const std::vector< double > & arcWeights() const
Half measured(const GradientOracle &oracle, const Eigen::VectorXd &x, Kind kind, const Options &options)
Full central difference of the oracle gradient: 2 d calls.
ArcTailNewtonStep solveArcTailNewton(const ArcTailEvaluation &state, const std::vector< M > &normals, const V &correction)
ArcTailForceGradientData prepareArcTailForceGradient(const Action &action, const std::vector< Eigen::VectorXd > &points, double duration, const std::vector< PotentialEvaluation > &native, const ArcTailPotential &potential, const ArcTailSearchOptions &options, const std::function< std::vector< PotentialEvaluation >(const std::vector< Eigen::VectorXd > &)> &ownedEvaluate)
ArcTailEvaluation evaluateArcTailForceGradient(const Action &action, const std::vector< Eigen::VectorXd > &points, const std::vector< PotentialEvaluation > &native, double duration, const ArcTailForceGradientData &data, const std::vector< Eigen::MatrixXd > &searchHessians={}, const std::vector< Eigen::MatrixXd > &searchThirdContractions={})
std::function< std::vector< PotentialEvaluation >(const std::vector< Eigen::VectorXd > &)> evaluate
std::function< std::vector< Eigen::MatrixXd >(const std::vector< Eigen::VectorXd > &)> searchHessians
std::vector< Eigen::VectorXd > path

◆ optimizeFixedTimeArc()

template<class Action>
ArcTailSearchResult gpr::quantum::optimizeFixedTimeArc ( const Action & action,
const std::vector< Eigen::VectorXd > & initial,
double duration,
const PathConstraints & constraints,
const ArcTailPotential & potential,
const ArcTailSearchOptions & options = fixedTimeArcOptions(),
const std::function< void(const ArcTailSearchResult &)> & retain = {},
double maximumDisplacement = std::numeric_limits<double>::infinity() )
inline

Definition at line 85 of file FixedTimeArc.h.

90 {},
91 double maximumDisplacement = std::numeric_limits<double>::infinity())
92{
93 using V = Eigen::VectorXd;
94 const auto n = initial.size();
95 const auto k = constraints.target.size();
96 if (n < 2 || action.arcWeights().size() + 1 != n ||
97 constraints.normals.size() != n || k < 1 ||
98 !(duration > 0 && duration < action.period()) || !potential.evaluate ||
99 !potential.searchHessians ||
100 !(options.forceTolerance > 0 && options.constraintTolerance > 0 &&
101 options.maximumStep > 0) ||
102 !std::isfinite(options.forceTolerance) ||
103 !std::isfinite(options.constraintTolerance) ||
104 !std::isfinite(options.maximumStep) || options.maximumBacktracks < 1 ||
105 !(maximumDisplacement > 0) || std::isnan(maximumDisplacement))
106 throw std::invalid_argument(
107 "Finite fixed-time arc controls and callbacks required");
108 if (options.reflectionEvenPath) {
109 if (options.referenceForceGradient)
110 throw std::invalid_argument(
111 "Reflection projection requires primitive fixed-time action");
112 validateReflectionEvenBand(initial, action.arcWeights(), constraints,
113 options.constraintTolerance);
114 }
115 const auto d = initial.front().size();
116 Eigen::MatrixXd gram = Eigen::MatrixXd::Zero(k, k);
117 if (d < 1 || !constraints.target.allFinite())
118 throw std::invalid_argument("Finite fixed-time arc metric required");
119 for (std::size_t j = 0; j < n; ++j) {
120 if (initial[j].size() != d || !initial[j].allFinite() ||
121 constraints.normals[j].rows() != d ||
122 constraints.normals[j].cols() != k ||
123 !constraints.normals[j].allFinite())
124 throw std::invalid_argument(
125 "Fixed-time arc node or constraint metric differs");
126 gram += constraints.normals[j].transpose() * constraints.normals[j];
127 }
128 if ((gram - Eigen::MatrixXd::Identity(k, k)).norm() > 1e-10)
129 throw std::invalid_argument(
130 "Fixed-time arc constraints must be jointly orthonormal");
131 auto coordinate = [&](const std::vector<V>& q) {
132 V out = V::Zero(k);
133 for (std::size_t j = 0; j < n; ++j)
134 out += constraints.normals[j].transpose() * q[j];
135 return out;
136 };
137 auto enforce = [&](std::vector<V>& q) {
138 const V delta = constraints.target - coordinate(q);
139 for (std::size_t j = 0; j < n; ++j)
140 q[j] += constraints.normals[j] * delta;
142 };
143 std::size_t calls = 0, batches = 0, hessians = 0, physicalActions = 0;
144 auto ownedEvaluate = [&](const std::vector<V>& q) {
145 auto out = potential.evaluate(q);
146 ++batches;
147 calls += q.size();
148 return out;
149 };
150 auto measure = [&](const std::vector<V>& q) {
152 out.path = q;
153 out.arcDuration = duration;
154 out.native = ownedEvaluate(q);
155 out.forceGradient = prepareArcTailForceGradient(
156 action, q, duration, out.native, potential, options, ownedEvaluate);
157 physicalActions += out.forceGradient.physicalHessianActionRequests;
159 action, q, out.native, duration, out.forceGradient);
160 V normal = V::Zero(k);
161 for (std::size_t j = 0; j < n; ++j)
162 normal +=
163 constraints.normals[j].transpose() * out.evaluation.gradient[j];
164 for (std::size_t j = 0; j < n; ++j) {
165 const double weight = .5 * duration *
166 ((j ? action.arcWeights()[j - 1] : 0) +
167 (j + 1 < n ? action.arcWeights()[j] : 0));
168 out.fullForce = std::max(
169 out.fullForce, out.evaluation.gradient[j].norm() / weight);
170 out.conditionalForce = std::max(
171 out.conditionalForce,
172 (out.evaluation.gradient[j] - constraints.normals[j] * normal)
173 .norm() /
174 weight);
175 }
176 out.energyResidual = std::abs(out.evaluation.durationGradient);
177 out.constraintResidual = (coordinate(q) - constraints.target).norm();
178 out.conditionalStationarityQualified =
179 out.conditionalForce <= options.forceTolerance &&
180 out.constraintResidual <= options.constraintTolerance;
181 out.fullStationarityQualified = out.conditionalStationarityQualified &&
182 out.fullForce <= options.forceTolerance;
183 out.converged = options.requireFullStationarity
184 ? out.fullStationarityQualified
185 : out.conditionalStationarityQualified;
186 out.evaluations = calls;
187 out.batchEvaluations = batches;
188 out.searchHessianEvaluations = hessians;
189 out.physicalHessianActionEvaluations = physicalActions;
190 return out;
191 };
192 auto merit = [&](const ArcTailSearchResult& q) {
193 return std::hypot(
194 (options.requireFullStationarity ? q.fullForce
195 : q.conditionalForce) /
196 options.forceTolerance,
197 q.constraintResidual / options.constraintTolerance);
198 };
199 auto points = initial;
200 enforce(points);
201 const auto center = points;
202 auto displacement = [&](const std::vector<V>& q) {
203 double distance = 0;
204 for (std::size_t j = 0; j < n; ++j)
205 distance = std::max(distance, (q[j] - center[j]).norm());
206 return distance;
207 };
208 auto restrict = [&](std::vector<V>& q) {
209 const double distance = displacement(q);
210 if (distance > maximumDisplacement) {
211 const double fraction = maximumDisplacement / distance;
212 for (std::size_t j = 0; j < n; ++j)
213 q[j] = center[j] + fraction * (q[j] - center[j]);
214 }
215 };
216 auto state = measure(points);
217 if (retain) retain(state);
218 for (std::size_t iteration = 0;
219 !state.converged && iteration < options.maximumIterations;
220 ++iteration) {
221 if (displacement(state.path) >=
222 maximumDisplacement *
223 (1 - 64 * std::numeric_limits<double>::epsilon())) {
224 state.failure =
225 "Fixed-time arc proposal reaches its trust boundary";
226 break;
227 }
228 const auto curvature = potential.searchHessians(state.path);
229 hessians += n;
230 std::vector<Eigen::MatrixXd> third;
231 if (state.forceGradient.enabled) {
232 const double epsilon = options.physicalHessianStep;
233 if (!(epsilon > 0) || !std::isfinite(epsilon))
234 throw std::invalid_argument(
235 "Positive finite compact arc third-contraction step "
236 "required");
237 third.assign(n, Eigen::MatrixXd::Zero(d, d));
238 std::vector<V> probes;
239 std::vector<std::size_t> active;
240 std::vector<double> norms;
241 for (std::size_t j = 0; j < n; ++j) {
242 const double norm =
243 state.forceGradient.residualGradients[j].norm();
244 if (norm == 0) continue;
245 const V shift =
246 epsilon * state.forceGradient.residualGradients[j] / norm;
247 active.push_back(j);
248 norms.push_back(norm);
249 probes.push_back(state.path[j] + shift);
250 probes.push_back(state.path[j] - shift);
251 }
252 if (!probes.empty()) {
253 const auto measured = potential.searchHessians(probes);
254 hessians += probes.size();
255 if (measured.size() != probes.size())
256 throw std::invalid_argument(
257 "Compact arc search Hessian probe count differs");
258 for (std::size_t i = 0; i < active.size(); ++i) {
259 const Eigen::MatrixXd contraction =
260 norms[i] * (measured[2 * i] - measured[2 * i + 1]) /
261 (2 * epsilon);
262 third[active[i]] =
263 (.5 * contraction + .5 * contraction.transpose())
264 .eval();
265 }
266 }
267 }
268 const auto quadratic = evaluateArcTailForceGradient(
269 action, state.path, state.native, duration, state.forceGradient,
270 curvature, third);
271 Eigen::MatrixXd normal(n * d, k);
272 for (std::size_t j = 0; j < n; ++j)
273 normal.middleRows(j * d, d) = constraints.normals[j];
274 const auto inertia = gaussian::restrictedTraceDeterminant(
275 quadratic.fluctuationSegments,
276 Eigen::MatrixXd::Identity(d, d), normal)
277 .inertia;
278 if (inertia.negative > 1 && !options.indexOneSearch) {
279 // Contraction toward the positive reactant reference selects a
280 // one-index branch before solving its nonlinear stationarity.
281 double radius = 0;
282 for (std::size_t j = 0; j < n; ++j)
283 radius =
284 std::max(radius, (state.path[j] - constraints.normals[j] *
285 constraints.target)
286 .norm());
287 const double fraction =
288 std::max(.5, 1 - options.maximumStep / radius);
289 auto candidate = state.path;
290 for (std::size_t j = 0; j < n; ++j) {
291 const V origin = constraints.normals[j] * constraints.target;
292 candidate[j] = origin + fraction * (candidate[j] - origin);
293 }
294 enforce(candidate);
295 restrict(candidate);
296 auto measured = measure(candidate);
297 measured.acceptedSteps = state.acceptedSteps + 1;
298 state = std::move(measured);
299 if (retain) retain(state);
300 continue;
301 }
303 try {
304 auto search = quadratic;
305 if (options.indexOneSearch && inertia.negative != 1)
306 search.fluctuationSegments =
307 indexOneArcKernel(quadratic.fluctuationSegments, normal)
308 .segments;
310 search, constraints.normals,
311 constraints.target - coordinate(state.path));
312 } catch (const std::exception& error) {
313 state.failure = error.what();
314 break;
315 }
316 double maximum = 0;
317 for (const auto& q: step.displacement)
318 maximum = std::max(maximum, q.norm());
319 double scale =
320 maximum > options.maximumStep ? options.maximumStep / maximum : 1.;
321 bool accepted = false;
322 for (std::size_t trial = 0; trial < options.maximumBacktracks;
323 ++trial, scale *= .5) {
324 auto candidate = state.path;
325 for (std::size_t j = 0; j < n; ++j)
326 candidate[j] += scale * step.displacement[j];
327 enforce(candidate);
328 restrict(candidate);
329 auto measured = measure(candidate);
330 std::vector<V> displacement;
331 for (std::size_t j = 0; j < n; ++j)
332 displacement.push_back(candidate[j] - state.path[j]);
333 const bool agreement =
334 options.indexOneSearch &&
336 measured.evaluation.action - state.evaluation.action,
337 quadraticArcActionChange(quadratic, displacement),
338 state.evaluation.action);
339 if (merit(measured) < merit(state) || agreement) {
340 measured.acceptedSteps = state.acceptedSteps + 1;
341 state = std::move(measured);
342 accepted = true;
343 if (retain) retain(state);
344 break;
345 }
346 }
347 if (!accepted) {
348 state.failure =
349 "Native fixed-time arc residual does not decrease along the "
350 "search step";
351 break;
352 }
353 }
354 if (!state.converged && state.failure.empty())
355 state.failure = "Maximum fixed-time arc iterations reached";
356 state.evaluations = calls;
357 state.batchEvaluations = batches;
358 state.searchHessianEvaluations = hessians;
359 state.physicalHessianActionEvaluations = physicalActions;
360 return state;
361}
void validateReflectionEvenBand(const std::vector< Eigen::VectorXd > &path, const std::vector< double > &weights, const Constraints &constraints, double tolerance)
IndexTargetedArcKernel indexOneArcKernel(const std::vector< gaussian::Segment > &segments, const Eigen::MatrixXd &normal)
bool arcActionChangeAgrees(double actual, double predicted, double scale)
ArcTailNewtonStep solveFixedTimeArcNewton(const ArcTailEvaluation &state, const std::vector< Eigen::MatrixXd > &normals, const Eigen::VectorXd &correction)
double quadraticArcActionChange(const ArcTailEvaluation &state, const std::vector< Eigen::VectorXd > &displacement)
double projectReflectionEvenBand(std::vector< Eigen::VectorXd > &path)

◆ optimizeGPArcTail()

template<class Model, class Action>
GPArcTailResult gpr::quantum::optimizeGPArcTail ( const Action & action,
const std::vector< Eigen::VectorXd > & initial,
double duration,
const PathConstraints & constraints,
const ArcTailPotential & potential,
Model & model,
const GPArcTailOptions & options = {},
const std::function< void(const GPArcTailResult &)> & retain = {} )

Definition at line 148 of file GPArcTailOptimizer.h.

152 {},
153 const std::function<void(const GPArcTailResult&)>& retain = {})
154{
155 if (!potential.evaluate || !potential.searchHessians ||
156 !(options.maximumProposalDisplacement > 0) ||
157 !std::isfinite(options.maximumProposalDisplacement) ||
158 options.maximumAttempts == 0 || !(options.surrogateHessianStep > 0) ||
159 !std::isfinite(options.surrogateHessianStep))
160 throw std::invalid_argument(
161 "Native callbacks and positive finite GP arc search scales are "
162 "required");
163 if (options.maximumLearningBatches &&
164 (!options.fixedTimeQuadrature ||
166 options.learningBatchSize == 0))
167 throw std::invalid_argument(
168 "Band learning requires primitive fixed-time action and a positive "
169 "batch size");
170 if (options.reflectionEvenProposals) {
171 if (!options.fixedTimeQuadrature ||
173 throw std::invalid_argument(
174 "Outgoing reflection requires primitive fixed-time proposals");
175 if constexpr (requires { action.arcWeights(); })
176 validateReflectionEvenBand(initial, action.arcWeights(),
177 constraints,
179 else
180 throw std::invalid_argument(
181 "Reflection search requires explicit imaginary-time links");
182 }
183 GPArcTailResult result;
184 if (options.initialNativePoints.size() !=
185 options.initialNativeValues.size() ||
186 (!options.initialNativePoints.empty() && initial.empty()))
187 throw std::invalid_argument(
188 "Matching initial native observations and a nonempty band "
189 "required");
190 for (std::size_t i = 0; i < options.initialNativePoints.size(); ++i)
191 if (options.initialNativePoints[i].size() != initial.front().size() ||
192 options.initialNativeValues[i].gradient.size() !=
193 initial.front().size() ||
194 !options.initialNativePoints[i].allFinite() ||
195 !options.initialNativeValues[i].gradient.allFinite() ||
196 !std::isfinite(options.initialNativeValues[i].energy))
197 throw std::invalid_argument(
198 "Initial native observations must match the finite band "
199 "metric");
200 if (!options.initialNativeTrialPoints.empty()) {
201 if (!options.fixedTimeQuadrature ||
202 options.initialNativeTrialPoints.size() != initial.size())
203 throw std::invalid_argument(
204 "A resumed native trial requires a complete fixed-time band");
205 for (const auto& point: options.initialNativeTrialPoints)
206 if (point.size() != initial.front().size() || !point.allFinite())
207 throw std::invalid_argument(
208 "A resumed native trial must match the finite band metric");
209 if (options.reflectionEvenProposals) {
210 if constexpr (requires { action.arcWeights(); })
212 action.arcWeights(), constraints,
214 }
215 }
216 auto initialRequiredPoints = options.initialNativePoints;
217 auto initialRequiredValues = options.initialNativeValues;
218 std::vector<Eigen::VectorXd> observedPoints = initialRequiredPoints;
219 std::vector<PotentialEvaluation> observedValues = initialRequiredValues;
220 bool initialMandatory = !observedPoints.empty();
221 if (initialMandatory) model.addObservations(observedPoints, observedValues);
222 result.initialNativeObservations = observedPoints.size();
223 auto observe = [&](const std::vector<Eigen::VectorXd>& q) {
224 auto values = potential.evaluate(q);
225 if (values.size() != q.size())
226 throw std::runtime_error("Native GP arc batch shape differs");
227 for (std::size_t j = 0; j < q.size(); ++j)
228 if (values[j].gradient.size() != q[j].size() ||
229 !values[j].gradient.allFinite() ||
230 !std::isfinite(values[j].energy))
231 throw std::runtime_error("Native GP arc return is nonfinite");
232 model.addObservations(q, values);
233 observedPoints.insert(observedPoints.end(), q.begin(), q.end());
234 observedValues.insert(observedValues.end(), values.begin(),
235 values.end());
236 result.nativeEvaluations += q.size();
237 ++result.nativeBatches;
238 return values;
239 };
240 ArcTailPotential owned{observe, potential.searchHessians,
241 potential.physicalHessianActions};
242 auto measuredOptions = options.native;
243 measuredOptions.maximumIterations = 0;
244 auto measure = [&](const auto& q, double t) {
245 auto state = options.fixedTimeQuadrature
246 ? optimizeFixedTimeArc(action, q, t, constraints,
247 owned, measuredOptions)
248 : optimizeArcTail(action, q, t, constraints, owned,
249 measuredOptions);
250 result.physicalHessianActions += state.physicalHessianActionEvaluations;
251 return state;
252 };
253 auto merit = [&](const ArcTailSearchResult& state,
254 double referenceDuration) {
255 const double force = options.native.requireFullStationarity
256 ? state.fullForce
257 : state.conditionalForce;
258 return std::hypot(
259 std::hypot(
260 force * state.arcDuration /
261 (referenceDuration * options.native.forceTolerance),
262 options.fixedTimeQuadrature
263 ? 0.
264 : state.energyResidual / options.native.energyTolerance),
265 state.constraintResidual / options.native.constraintTolerance);
266 };
267 result.native = measure(initial, duration);
268 auto publish = [&]() {
269 result.native.evaluations = result.nativeEvaluations;
270 result.native.batchEvaluations = result.nativeBatches;
271 result.native.physicalHessianActionEvaluations =
272 result.physicalHessianActions;
273 if (retain) retain(result);
274 };
275 publish();
276 if (!result.native.converged && !options.initialNativeTrialPoints.empty()) {
277 auto trial = measure(options.initialNativeTrialPoints, duration);
278 ++result.resumedNativeTrials;
279 if (trial.converged ||
280 merit(trial, duration) < merit(result.native, duration)) {
281 trial.acceptedSteps = result.native.acceptedSteps + 1;
282 result.native = std::move(trial);
283 initialMandatory = false;
284 ++result.acceptedResumedNativeTrials;
285 } else {
286 initialRequiredPoints.insert(initialRequiredPoints.end(),
287 trial.path.begin(), trial.path.end());
288 initialRequiredValues.insert(initialRequiredValues.end(),
289 trial.native.begin(),
290 trial.native.end());
291 initialMandatory = true;
292 ++result.rejectedProposals;
293 }
294 publish();
295 }
296 for (std::size_t outer = 0;
297 outer < options.maximumOuterIterations && !result.native.converged;
298 ++outer) {
299 result.outerIterations = outer + 1;
300 double radius = options.maximumProposalDisplacement;
301 bool accepted = false;
302 using LearningSample = std::pair<Eigen::VectorXd, PotentialEvaluation>;
303 std::vector<std::optional<LearningSample>> latestLearning(
304 initial.size());
305 std::size_t learningBatches = 0;
306 for (std::size_t attempt = 0; attempt < options.maximumAttempts;) {
307 auto fittingPoints = result.native.path;
308 auto fittingValues = result.native.native;
309 if (options.maximumLearningBatches || initialMandatory ||
310 std::any_of(
311 latestLearning.begin(), latestLearning.end(),
312 [](const auto& sample) { return sample.has_value(); })) {
313 fittingPoints.clear();
314 fittingValues.clear();
315 auto append = [&](const auto& point, const auto& value) {
316 if (std::none_of(fittingPoints.begin(), fittingPoints.end(),
317 [&](const auto& q) {
318 return sameGPBandPoint(q, point);
319 })) {
320 fittingPoints.push_back(point);
321 fittingValues.push_back(value);
322 }
323 };
324 for (std::size_t j = 0; j < result.native.path.size(); ++j)
325 append(result.native.path[j], result.native.native[j]);
326 if (initialMandatory)
327 for (std::size_t j = 0; j < initialRequiredPoints.size();
328 ++j)
329 append(initialRequiredPoints[j],
330 initialRequiredValues[j]);
331 for (const auto& sample: latestLearning)
332 if (sample) append(sample->first, sample->second);
333 }
334 if (options.maximumTrainingSites) {
335 if constexpr (requires {
336 model.refitLocal(result.native.path,
337 result.native.native,
338 std::size_t{});
339 })
340 model.refitLocal(fittingPoints, fittingValues,
341 std::max(options.maximumTrainingSites,
342 fittingPoints.size()));
343 else
344 throw std::invalid_argument(
345 "The GP model does not support bounded local fitting");
346 } else
347 model.refit(observedPoints, observedValues);
348 ++result.refits;
349 if constexpr (requires { model.fittedObservations(); })
350 result.fittedObservations = model.fittedObservations();
351 if (options.maximumConditionedArchiveSites) {
352 if constexpr (requires {
353 model.conditionArchivedAround(
354 result.native.path, std::size_t{});
355 })
356 result.conditionedArchiveObservations =
357 model.conditionArchivedAround(
358 result.native.path,
360 else
361 throw std::invalid_argument(
362 "The GP model does not support archived native "
363 "conditioning");
364 }
366 surrogate.evaluate = [&](const auto& q) {
367 result.surrogateEvaluations += q.size();
368 return model.evaluate(q);
369 };
370 surrogate.searchHessians = [&](const auto& q) {
371 return detail::gpArcTailSearchHessians(
372 model, q, surrogate.evaluate, options.surrogateHessianStep,
373 result);
374 };
375 auto inner = options.native;
377 inner.maximumIterations = options.innerIterations;
378 const auto proposal =
379 options.fixedTimeQuadrature
381 action, result.native.path, result.native.arcDuration,
382 constraints, surrogate, inner, {}, radius)
383 : optimizeArcTail(action, result.native.path,
384 result.native.arcDuration, constraints,
385 surrogate, inner);
386 double displacement = 0;
387 for (std::size_t j = 0; j < proposal.path.size(); ++j)
388 displacement =
389 std::max(displacement,
390 (proposal.path[j] - result.native.path[j]).norm());
391 const double dt = proposal.arcDuration - result.native.arcDuration;
392 if (displacement <= 1e-14 && std::abs(dt) <= 1e-14) break;
393 double fraction =
394 displacement > radius ? radius / displacement : 1.;
395 if (dt != 0)
396 fraction = std::min(
397 fraction,
399 std::min(result.native.arcDuration,
400 action.period() - result.native.arcDuration) /
401 std::abs(dt));
402 auto candidate = result.native.path;
403 for (std::size_t j = 0; j < candidate.size(); ++j)
404 candidate[j] += fraction * (proposal.path[j] - candidate[j]);
405 const double candidateDuration =
406 result.native.arcDuration + fraction * dt;
407 if (options.reflectionEvenProposals) {
408 result.maximumReflectionCorrection =
409 std::max(result.maximumReflectionCorrection,
410 projectReflectionEvenBand(candidate));
411 ++result.reflectedProposals;
412 }
413 if (learningBatches < options.maximumLearningBatches) {
414 if constexpr (requires {
415 action.arcWeights();
416 model.posteriorPointVariance(candidate)
417 .front()
418 .massGradientTrace;
419 }) {
420 const auto uncertainty =
421 model.posteriorPointVariance(candidate);
422 if (uncertainty.size() != candidate.size())
423 throw std::runtime_error(
424 "Band variance batch dimensions differ");
425 std::vector<double> trace;
426 for (const auto& item: uncertainty)
427 trace.push_back(item.massGradientTrace);
428 Eigen::VectorXd weights =
429 Eigen::VectorXd::Zero(candidate.size());
430 const auto& links = action.arcWeights();
431 if (links.size() + 1 != candidate.size())
432 throw std::runtime_error(
433 "Band acquisition action dimensions differ");
434 for (std::size_t j = 0; j < links.size(); ++j) {
435 const double w = .5 * candidateDuration * links[j];
436 weights[j] += w;
437 weights[j + 1] += w;
438 }
439 const auto selected = selectGPBandNodes(
440 candidate, trace, weights, observedPoints,
441 options.learningBatchSize);
442 if (!selected.empty()) {
443 std::vector<Eigen::VectorXd> queries;
444 for (const auto& item: selected)
445 queries.push_back(candidate[item.node]);
446 const auto values = observe(queries);
447 for (std::size_t j = 0; j < selected.size(); ++j)
448 latestLearning[selected[j].node] =
449 LearningSample{queries[j], values[j]};
450 ++learningBatches;
451 ++result.learningBatches;
452 result.learningNativeValues += queries.size();
453 publish();
454 continue;
455 }
456 } else
457 throw std::invalid_argument(
458 "Band learning requires mass-gradient posterior "
459 "variance");
460 }
461 const bool useAgreement =
462 options.native.indexOneSearch && options.fixedTimeQuadrature;
463 double predictedChange = 0;
464 if (useAgreement) {
465 auto predictedAction = [&](const auto& q, double duration) {
466 const auto values = surrogate.evaluate(q);
467 const auto correction = prepareArcTailForceGradient(
468 action, q, duration, values, surrogate, options.native,
469 surrogate.evaluate);
470 return evaluateArcTailForceGradient(action, q, values,
471 duration, correction)
472 .action;
473 };
474 const auto predictedCurrent = predictedAction(
475 result.native.path, result.native.arcDuration);
476 const auto predictedNext =
477 predictedAction(candidate, candidateDuration);
478 predictedChange = predictedNext - predictedCurrent;
479 }
480 // Native observations invalidate a fitted model. The prediction
481 // belongs to the fit that proposed this displacement.
482 auto next = measure(candidate, candidateDuration);
483 const bool agreement =
484 useAgreement &&
486 next.evaluation.action - result.native.evaluation.action,
487 predictedChange, result.native.evaluation.action);
488 if (merit(next, result.native.arcDuration) <
489 merit(result.native, result.native.arcDuration) ||
490 agreement) {
491 next.acceptedSteps = result.native.acceptedSteps + 1;
492 result.native = std::move(next);
493 initialMandatory = false;
494 accepted = true;
495 publish();
496 break;
497 }
498 // Rejected native bands are mandatory observations in local refits.
499 for (std::size_t j = 0; j < next.path.size(); ++j)
500 latestLearning[j] =
501 LearningSample{next.path[j], next.native[j]};
502 ++result.rejectedProposals;
503 ++attempt;
504 radius *= .5;
505 }
506 if (!accepted) {
507 result.native.failure =
508 "No native residual decrease from GP fixed-period proposals";
509 publish();
510 return result;
511 }
512 }
513 if (result.native.converged)
514 result.native.failure.clear();
515 else
516 result.native.failure =
517 "Maximum GP fixed-period arc iterations reached";
518 publish();
519 return result;
520}
Half surrogate(GaussianProcessRegression &gp, const Eigen::VectorXd &x, Kind kind, const Options &options)
ArcTailSearchResult optimizeFixedTimeArc(const Action &action, const std::vector< Eigen::VectorXd > &initial, double duration, const PathConstraints &constraints, const ArcTailPotential &potential, const ArcTailSearchOptions &options=fixedTimeArcOptions(), const std::function< void(const ArcTailSearchResult &)> &retain={}, double maximumDisplacement=std::numeric_limits< double >::infinity())
std::vector< GPBandNodeScore > selectGPBandNodes(const std::vector< Eigen::VectorXd > &points, const std::vector< double > &massGradientVariance, const Eigen::VectorXd &weights, const std::vector< Eigen::VectorXd > &measured, std::size_t maximumNodes)
ArcTailSearchResult optimizeArcTail(const ArcTailAction &action, const std::vector< V > &initial, double duration, const PathConstraints &constraints, const ArcTailPotential &potential, const ArcTailSearchOptions &options, const std::function< void(const ArcTailSearchResult &)> &retain)
std::function< std::vector< Eigen::VectorXd >(const std::vector< Eigen::VectorXd > &, const std::vector< Eigen::VectorXd > &)> physicalHessianActions
std::vector< Eigen::VectorXd > initialNativePoints
std::vector< PotentialEvaluation > initialNativeValues
std::vector< Eigen::VectorXd > initialNativeTrialPoints

◆ optimizeGPLineIntegralNEB()

template<class Model>
GPLineIntegralNEBResult gpr::quantum::optimizeGPLineIntegralNEB ( const std::vector< Eigen::VectorXd > & initial,
const LineIntegralNEBBatch & potential,
Model & model,
const GPLineIntegralNEBOptions & options = {},
const std::function< void(const GPLineIntegralNEBResult &)> & retain = {} )

Definition at line 933 of file GPLineIntegralNEB.h.

936 {},
937 const std::function<void(const GPLineIntegralNEBResult&)>& retain = {})
938{
939 if (!(options.maximumProposalDisplacement > 0) ||
940 !std::isfinite(options.maximumProposalDisplacement) || !potential)
941 throw std::invalid_argument(
942 "Positive finite GP proposal radius and native calculator "
943 "required");
944 if (options.path.jctcCompatible && options.stringMethod)
945 throw std::invalid_argument(
946 "JCTC-compatible constraints require the LI-NEB path method");
947 GPLineIntegralNEBResult result;
948 std::vector<Eigen::VectorXd> measuredPoints;
949 std::vector<PotentialEvaluation> measuredValues;
950 auto observe = [&](const auto& q) {
951 auto values = potential(q);
952 if (values.size() != q.size())
953 throw std::runtime_error("Native GP LI-NEB batch shape mismatch");
954 measuredPoints.insert(measuredPoints.end(), q.begin(), q.end());
955 measuredValues.insert(measuredValues.end(), values.begin(),
956 values.end());
957 return values;
958 };
959 auto native = [&](const auto& q) {
960 ++result.native.batchEvaluations;
961 result.native.evaluations += q.size();
962 return observe(q);
963 };
964 LineIntegralFIREState fireState;
965 auto measured = [&](const auto& q, const auto& v) {
966 const auto& o = options.path;
967 double spring = o.spring, contour = o.contour,
968 contourRight = o.contourRight;
969 if (o.jctcCompatible && fireState.initialized &&
970 fireState.constraintsInitialized) {
971 spring = fireState.spring;
972 contour = fireState.contourLeft;
973 contourRight = fireState.contourRight;
974 }
975 return evaluateLineIntegralNEB(q, v, o.energy, spring, contour, o.hbar,
976 o.action, o.jctcCompatible, contourRight,
977 o.actionForceCutoff);
978 };
979 auto forceCriteria = [&](const LineIntegralNEBState& state) {
980 return state.maximumForce < options.path.forceTolerance &&
981 (!options.path.jctcCompatible ||
982 state.transverseForceSum <
984 };
985 auto contourCriteria = [&](const LineIntegralNEBState& state) {
986 return options.path.jctcCompatible ||
987 state.endpointEnergyError < options.path.energyTolerance;
988 };
989 auto nativeCriteria = [&](const LineIntegralNEBState& state) {
990 return forceCriteria(state) && contourCriteria(state) &&
991 state.turningOrientationsQualified;
992 };
993 result.native.path = initial;
994 result.native.native = native(initial);
995 result.native.state = measured(initial, result.native.native);
996 for (std::size_t outer = 0; outer <= options.maximumOuterIterations;
997 ++outer) {
998 result.outerIterations = outer;
999 auto& current = result.native;
1000 // Native Newton corrections close the contour independently of the GP
1001 // interpolation error. Only the two changed endpoints require new
1002 // forces.
1003 for (int correction = 0; correction < 12; ++correction) {
1004 std::vector<Eigen::VectorXd> endpoints;
1005 std::vector<std::size_t> indices;
1006 for (auto j: {std::size_t(0), current.path.size() - 1}) {
1007 const auto& value = current.native[j];
1008 const double residual = value.energy - options.path.energy;
1009 if (std::abs(residual) < .2 * options.path.energyTolerance)
1010 continue;
1011 const double norm2 = value.gradient.squaredNorm();
1012 if (!(norm2 > 0) || !std::isfinite(norm2))
1013 throw std::domain_error(
1014 "Native turning contour has no finite normal");
1015 Eigen::VectorXd step = -residual / norm2 * value.gradient;
1016 if (step.norm() > options.maximumProposalDisplacement)
1017 step *= options.maximumProposalDisplacement / step.norm();
1018 endpoints.push_back(current.path[j] + step);
1019 indices.push_back(j);
1020 }
1021 if (indices.empty()) break;
1022 const auto values = native(endpoints);
1023 if (values.size() != indices.size())
1024 throw std::runtime_error("Native contour batch shape mismatch");
1025 for (std::size_t k = 0; k < indices.size(); ++k) {
1026 current.path[indices[k]] = endpoints[k];
1027 current.native[indices[k]] = values[k];
1028 }
1029 }
1030 current.state = measured(current.path, current.native);
1031 current.converged = nativeCriteria(current.state);
1032 if (retain) retain(result);
1033 if (!current.state.turningOrientationsQualified &&
1034 forceCriteria(current.state) && contourCriteria(current.state)) {
1035 current.failure =
1036 "LI-NEB turning orientation does not enter the forbidden "
1037 "region";
1038 return result;
1039 }
1040 if (current.converged) {
1041 current.failure.clear();
1042 return result;
1043 }
1044 if (outer == options.maximumOuterIterations) break;
1045 model.refit(measuredPoints, measuredValues);
1046 ++result.refits;
1047 auto inner = options.path;
1048 inner.maximumIterations = options.innerIterations;
1049 inner.geometricPreconditioning = options.geometricSurrogateForces;
1050 auto surrogate = [&](const auto& q) {
1051 result.surrogateEvaluations += q.size();
1052 return model.evaluate(q);
1053 };
1054 auto propose = [&]() {
1055 auto path = current.path;
1056 try {
1057 path = (options.stringMethod
1058 ? optimizeLineIntegralString(current.path,
1059 surrogate, inner)
1061 current.path, surrogate, inner, {},
1062 options.path.jctcCompatible ? &fireState
1063 : nullptr))
1064 .path;
1065 } catch (const std::domain_error&) {
1066 }
1067 return path;
1068 };
1069 auto proposal = propose();
1070 bool accepted = false;
1071 double radius = options.maximumProposalDisplacement;
1072 for (int attempt = 0; attempt < 12; ++attempt) {
1073 double maximum = 0;
1074 for (std::size_t j = 0; j < proposal.size(); ++j)
1075 maximum =
1076 std::max(maximum, (proposal[j] - current.path[j]).norm());
1077 if (maximum <= 1e-12) break;
1078 const double fraction = maximum > radius ? radius / maximum : 1.;
1079 auto trial = current.path;
1080 for (std::size_t j = 0; j < trial.size(); ++j)
1081 trial[j] += fraction * (proposal[j] - current.path[j]);
1082 auto values = native(trial);
1083 auto restoration = options.path;
1084 restoration.maximumStep = radius;
1085 const auto repaired = restoreLineIntegralInterior(
1086 trial, values, current.native, restoration, native,
1088 result.interiorCorrectionBatches += repaired.batchEvaluations;
1089 result.interiorCorrectionPoints += repaired.pointEvaluations;
1090 double restoredDisplacement = 0;
1091 for (std::size_t j = 0; j < trial.size(); ++j)
1092 restoredDisplacement = std::max(
1093 restoredDisplacement, (trial[j] - current.path[j]).norm());
1094 try {
1095 auto state = measured(trial, values);
1096 // No GP-only stationarity or action is reported as native
1097 // evidence.
1098 if (state.turningOrientationsQualified &&
1099 restoredDisplacement > 1e-12 &&
1100 (options.proposalAcceptance ==
1102 state.maximumForce < current.state.maximumForce)) {
1103 current.path = std::move(trial);
1104 current.native = std::move(values);
1105 current.state = std::move(state);
1106 accepted = true;
1107 break;
1108 }
1109 } catch (const std::domain_error&) {
1110 }
1111 // Rejected native bands and contour corrections remain training
1112 // data. Each new proposal uses those forces inside a contracted
1113 // trust region.
1114 model.refit(measuredPoints, measuredValues);
1115 ++result.refits;
1116 proposal = propose();
1117 radius *= .5;
1118 }
1119 if (!accepted) {
1120 auto recovery = options.path;
1122 const auto savedCalls = current.evaluations,
1123 savedBatches = current.batchEvaluations;
1124 auto recovered = optimizeLineIntegralNEB(
1125 current.path, observe, recovery, {},
1126 options.path.jctcCompatible ? &fireState : nullptr);
1127 recovered.evaluations += savedCalls;
1128 recovered.batchEvaluations += savedBatches;
1129 current = std::move(recovered);
1130 }
1131 ++current.iterations;
1132 }
1133 result.native.failure = "GP LI-NEB outer iteration limit";
1134 return result;
1135}
LineIntegralFeasibilityResult restoreLineIntegralInterior(std::vector< Eigen::VectorXd > &trial, std::vector< PotentialEvaluation > &values, const std::vector< PotentialEvaluation > &source, const LineIntegralNEBOptions &options, const LineIntegralNEBBatch &native, std::size_t maximumCorrections=4)
LineIntegralNEBResult optimizeLineIntegralNEB(const std::vector< Eigen::VectorXd > &initial, const LineIntegralNEBBatch &potential, const LineIntegralNEBOptions &options={}, const std::function< void(const LineIntegralNEBResult &)> &retain={}, LineIntegralFIREState *fireState=nullptr, const std::function< bool(const std::vector< Eigen::VectorXd > &)> &earlyStop={})
LineIntegralNEBResult optimizeLineIntegralString(const std::vector< Eigen::VectorXd > &initial, const LineIntegralNEBBatch &potential, const LineIntegralNEBOptions &options={}, const std::function< void(const LineIntegralNEBResult &)> &retain={}, LineIntegralFIREState *fireState=nullptr)
LineIntegralProposalAcceptance proposalAcceptance

◆ optimizeLineIntegralNEB()

LineIntegralNEBResult gpr::quantum::optimizeLineIntegralNEB ( const std::vector< Eigen::VectorXd > & initial,
const LineIntegralNEBBatch & potential,
const LineIntegralNEBOptions & options = {},
const std::function< void(const LineIntegralNEBResult &)> & retain = {},
LineIntegralFIREState * fireState = nullptr,
const std::function< bool(const std::vector< Eigen::VectorXd > &)> & earlyStop = {} )
inline

Definition at line 456 of file LineIntegralNEB.h.

459 {},
460 const std::function<void(const LineIntegralNEBResult&)>& retain = {},
461 LineIntegralFIREState* fireState = nullptr,
462 const std::function<bool(const std::vector<Eigen::VectorXd>&)>& earlyStop =
463 {})
464{
465 if (!potential || initial.size() < 3 || !(options.timeStep > 0) ||
466 !(options.maximumTimeStep >= options.timeStep) ||
467 !(options.maximumStep > 0) || !(options.forceTolerance > 0) ||
468 !(options.energyTolerance > 0) ||
469 !(options.initialMixing >= 0 && options.initialMixing <= 1) ||
470 !(options.minimumTimeStep >= 0 &&
471 options.minimumTimeStep <= options.timeStep) ||
472 !std::isfinite(options.initialMixing) ||
473 !std::isfinite(options.minimumTimeStep) ||
474 !std::isfinite(options.maximumTimeStep) ||
475 !std::isfinite(options.maximumStep) ||
476 !std::isfinite(options.forceTolerance) ||
477 !std::isfinite(options.energyTolerance) ||
478 !(options.actionForceCutoff >= 0) ||
479 !std::isfinite(options.actionForceCutoff) ||
480 !(options.endpointEnergyConvergeValue > 0) ||
481 !std::isfinite(options.endpointEnergyConvergeValue) ||
482 !(options.endpointGradientTolerance > 0) ||
483 !std::isfinite(options.endpointGradientTolerance) ||
484 !(options.transverseForceSumTolerance > 0) ||
485 !std::isfinite(options.transverseForceSumTolerance) ||
486 !(options.springForceFloor > 0) ||
487 !std::isfinite(options.springForceFloor) ||
489 throw std::invalid_argument(
490 "Finite positive LI-NEB search controls required");
492 result.path = initial;
493 auto evaluate = [&](const auto& p) {
494 ++result.batchEvaluations;
495 result.evaluations += p.size();
496 return potential(p);
497 };
498 LineIntegralNEBOptions active = options;
499 auto state = [&](const auto& p, const auto& v) {
501 p, v, active.energy, active.spring, active.contour, active.hbar,
502 active.action, active.jctcCompatible, active.contourRight,
503 active.actionForceCutoff);
504 };
505 std::vector<Eigen::VectorXd> velocity(
506 initial.size(), Eigen::VectorXd::Zero(initial.front().size()));
507 double dt = options.timeStep, alpha = options.initialMixing;
508 std::size_t positive = 0, negative = 0, totalSteps = 0;
509 if (fireState && fireState->initialized) {
510 if (fireState->velocity.size() != initial.size() ||
511 !(fireState->timeStep > 0) || !std::isfinite(fireState->timeStep) ||
512 !(fireState->mixing >= 0 && fireState->mixing <= 1) ||
513 !std::isfinite(fireState->mixing))
514 throw std::invalid_argument(
515 "Finite matching LI-NEB FIRE state required");
516 for (std::size_t j = 0; j < initial.size(); ++j)
517 if (fireState->velocity[j].size() != initial.front().size() ||
518 !fireState->velocity[j].allFinite())
519 throw std::invalid_argument(
520 "Matching finite LI-NEB FIRE velocities required");
521 velocity = fireState->velocity;
522 dt = std::min(fireState->timeStep, options.maximumTimeStep);
523 if (options.minimumTimeStep > 0)
524 dt = std::max(dt, options.minimumTimeStep);
525 alpha = fireState->mixing;
526 positive = fireState->positiveSteps;
527 negative = fireState->negativeSteps;
528 totalSteps = fireState->steps;
529 if (options.jctcCompatible && fireState->constraintsInitialized) {
530 active.spring = fireState->spring;
531 active.contour = fireState->contourLeft;
532 active.contourRight = fireState->contourRight;
533 }
534 }
535 auto saveFireState = [&] {
536 if (!fireState) return;
537 fireState->velocity = velocity;
538 fireState->timeStep = dt;
539 fireState->mixing = alpha;
540 fireState->positiveSteps = positive;
541 fireState->negativeSteps = negative;
542 fireState->steps = totalSteps;
543 fireState->spring = active.spring;
544 fireState->contourLeft = active.contour;
545 fireState->contourRight = active.contourRight;
546 fireState->constraintsInitialized = options.jctcCompatible;
547 fireState->initialized = true;
548 };
549 result.native = evaluate(result.path);
550 result.state = state(result.path, result.native);
551 auto adaptJctcConstraints = [&] {
552 if (!options.jctcCompatible) return;
553 double pathLength = 0.;
554 for (std::size_t j = 1; j < result.path.size(); ++j)
555 pathLength += (result.path[j] - result.path[j - 1]).norm();
556 double averageActionForce = 0.;
557 for (std::size_t j = 1; j + 1 < result.state.actionForce.size(); ++j)
558 averageActionForce += result.state.actionForce[j].norm();
559 averageActionForce /= double(result.state.actionForce.size() - 2);
560 averageActionForce =
561 std::max(averageActionForce, options.springForceFloor);
562 active.spring = averageActionForce /
563 (pathLength / (10. * double(result.path.size())));
564 auto endpointKappa = [&](std::size_t j) {
565 const double maxForce =
566 std::max(1e-3, result.native[j].gradient.cwiseAbs().maxCoeff());
567 double kappa = .2 / (maxForce * dt * dt);
568 if (std::abs(result.native[j].energy - options.energy) <
570 const double cap = .2 * options.endpointGradientTolerance /
572 kappa = std::min(kappa, cap);
573 }
574 return kappa;
575 };
576 active.contour = endpointKappa(0);
577 active.contourRight = endpointKappa(result.path.size() - 1);
578 };
579 auto searchForce = lineIntegralSearchForces(result.path, result.native,
580 result.state, active);
581 const bool storedConstraints = fireState && fireState->initialized &&
582 fireState->constraintsInitialized &&
583 options.jctcCompatible;
584 if (!storedConstraints) adaptJctcConstraints();
585 result.state = state(result.path, result.native);
586 searchForce = lineIntegralSearchForces(result.path, result.native,
587 result.state, active);
588 for (std::size_t iteration = 0; iteration <= options.maximumIterations;
589 ++iteration) {
590 result.iterations = iteration;
591 if (retain) retain(result);
592 const bool forceCriteria =
593 result.state.maximumForce < options.forceTolerance &&
594 (!options.jctcCompatible ||
595 result.state.transverseForceSum <
597 const bool contourCriteria =
598 options.jctcCompatible ||
599 result.state.endpointEnergyError < options.energyTolerance;
600 if (earlyStop && earlyStop(result.path)) {
601 result.trustRegionExit = true;
602 result.failure = "LI-NEB native trust region exited";
603 saveFireState();
604 return result;
605 }
606 if (forceCriteria && contourCriteria) {
607 if (!result.state.turningOrientationsQualified) {
608 result.failure =
609 "LI-NEB turning orientation does not enter the forbidden "
610 "region";
611 saveFireState();
612 return result;
613 }
614 result.converged = true;
615 saveFireState();
616 return result;
617 }
618 if (iteration == options.maximumIterations) break;
619 if (options.jctcCompatible && totalSteps > 0 &&
620 totalSteps % options.constraintUpdateInterval == 0) {
621 adaptJctcConstraints();
622 result.state = state(result.path, result.native);
623 searchForce = lineIntegralSearchForces(result.path, result.native,
624 result.state, active);
625 }
626 auto base = result.path;
627 auto trial = base;
628 std::vector<Eigen::VectorXd> step(initial.size());
629 double scale = 1.;
630 if (options.jctcCompatible) {
631 double power = 0., velocitySquared = 0., forceSquared = 0.;
632 for (std::size_t j = 0; j < trial.size(); ++j) {
633 power += velocity[j].dot(searchForce[j]);
634 velocitySquared += velocity[j].squaredNorm();
635 forceSquared += searchForce[j].squaredNorm();
636 }
637 if (power > 0.) {
638 ++positive;
639 negative = 0;
640 if (positive > 5) {
641 dt = std::min(dt * 1.1, options.maximumTimeStep);
642 alpha *= .99;
643 }
644 } else {
645 positive = 0;
646 ++negative;
647 if (negative > 100) {
648 result.failure =
649 "LI-NEB FIRE exceeded the uphill-step limit";
650 saveFireState();
651 return result;
652 }
653 dt = options.minimumTimeStep > 0
654 ? std::max(dt * .5, options.minimumTimeStep)
655 : dt * .5;
656 alpha = options.initialMixing;
657 for (std::size_t j = 0; j < trial.size(); ++j) {
658 base[j] -= .5 * dt * velocity[j];
659 velocity[j].setZero();
660 }
661 }
662 for (std::size_t j = 0; j < trial.size(); ++j)
663 velocity[j] += dt * searchForce[j];
664 if (power > 0. && forceSquared > 0.) {
665 velocitySquared = 0.;
666 for (const auto& v: velocity)
667 velocitySquared += v.squaredNorm();
668 const double velocityNorm = std::sqrt(velocitySquared);
669 const double forceNorm = std::sqrt(forceSquared);
670 for (std::size_t j = 0; j < trial.size(); ++j)
671 velocity[j] =
672 (1. - alpha) * velocity[j] +
673 alpha * velocityNorm / forceNorm * searchForce[j];
674 }
675 double displacementSquared = 0.;
676 for (std::size_t j = 0; j < trial.size(); ++j) {
677 step[j] = dt * velocity[j];
678 displacementSquared += step[j].squaredNorm();
679 }
680 const double displacementNorm = std::sqrt(displacementSquared);
681 if (displacementNorm > options.maximumStep)
682 scale = options.maximumStep / displacementNorm;
683 } else {
684 double largest = 0.;
685 for (std::size_t j = 0; j < trial.size(); ++j) {
686 step[j] = dt * velocity[j] + .5 * dt * dt * searchForce[j];
687 largest = std::max(largest, step[j].norm());
688 }
689 scale = largest > options.maximumStep
690 ? options.maximumStep / largest
691 : 1.;
692 }
693 std::vector<PotentialEvaluation> next;
694 LineIntegralNEBState nextState;
695 bool accepted = false;
696 double fraction = scale;
697 const int maximumBacktracks = options.jctcCompatible ? 1 : 24;
698 for (int backtrack = 0; backtrack < maximumBacktracks; ++backtrack) {
699 for (std::size_t j = 0; j < trial.size(); ++j)
700 trial[j] = base[j] + fraction * step[j];
701 next = evaluate(trial);
702 try {
703 nextState = state(trial, next);
704 accepted = true;
705 break;
706 } catch (const std::domain_error&) {
707 fraction *= .5;
708 }
709 }
710 if (!accepted) {
711 result.failure =
712 "No admissible LI-NEB step in the forbidden region";
713 saveFireState();
714 return result;
715 }
716 auto nextSearchForce =
717 lineIntegralSearchForces(trial, next, nextState, active);
718 if (!options.jctcCompatible) {
719 double power = 0., vv = 0., ff = 0.;
720 for (std::size_t j = 0; j < trial.size(); ++j) {
721 velocity[j] += .5 * dt * (searchForce[j] + nextSearchForce[j]);
722 power += velocity[j].dot(nextSearchForce[j]);
723 vv += velocity[j].squaredNorm();
724 ff += nextSearchForce[j].squaredNorm();
725 }
726 if (power > 0 && fraction == scale) {
727 ++positive;
728 if (ff > 0)
729 for (std::size_t j = 0; j < trial.size(); ++j)
730 velocity[j] =
731 (1 - alpha) * velocity[j] +
732 alpha * std::sqrt(vv / ff) * nextSearchForce[j];
733 if (positive > 5) {
734 dt = std::min(dt * 1.1, options.maximumTimeStep);
735 alpha *= .99;
736 }
737 } else {
738 positive = 0;
739 dt = options.minimumTimeStep > 0
740 ? std::max(options.minimumTimeStep, dt * .5)
741 : dt * .5;
742 alpha = options.initialMixing;
743 for (auto& v: velocity)
744 v.setZero();
745 }
746 }
747 result.path = std::move(trial);
748 result.native = std::move(next);
749 result.state = std::move(nextState);
750 searchForce = std::move(nextSearchForce);
751 ++totalSteps;
752 if (!(dt > std::numeric_limits<double>::epsilon())) {
753 result.failure = "LI-NEB time step underflows";
754 saveFireState();
755 return result;
756 }
757 }
758 result.failure = "LI-NEB iteration limit";
759 saveFireState();
760 return result;
761}
std::vector< Eigen::VectorXd > lineIntegralSearchForces(const std::vector< Eigen::VectorXd > &q, const std::vector< PotentialEvaluation > &values, const LineIntegralNEBState &state, const LineIntegralNEBOptions &options)
double forceNorm(const Eigen::MatrixBase< Derived > &force, ConvergenceNormType norm)
Definition ForceNorm.h:45
std::vector< Eigen::VectorXd > velocity

◆ optimizeLineIntegralString()

LineIntegralNEBResult gpr::quantum::optimizeLineIntegralString ( const std::vector< Eigen::VectorXd > & initial,
const LineIntegralNEBBatch & potential,
const LineIntegralNEBOptions & options = {},
const std::function< void(const LineIntegralNEBResult &)> & retain = {},
LineIntegralFIREState * fireState = nullptr )
inline

Definition at line 171 of file LineIntegralString.h.

174 {},
175 const std::function<void(const LineIntegralNEBResult&)>& retain = {},
176 LineIntegralFIREState* fireState = nullptr)
177{
178 if (!potential || initial.size() < 3 || !(options.timeStep > 0.) ||
179 !(options.maximumTimeStep >= options.timeStep) ||
180 !(options.maximumStep > 0.) || !(options.forceTolerance > 0.) ||
181 !(options.energyTolerance > 0.) ||
182 !(options.initialMixing >= 0. && options.initialMixing <= 1.) ||
183 !(options.minimumTimeStep >= 0. &&
184 options.minimumTimeStep <= options.timeStep) ||
185 !std::isfinite(options.initialMixing) ||
186 !std::isfinite(options.minimumTimeStep) ||
187 !std::isfinite(options.maximumTimeStep) ||
188 !std::isfinite(options.maximumStep) ||
189 !std::isfinite(options.forceTolerance) ||
190 !std::isfinite(options.energyTolerance))
191 throw std::invalid_argument(
192 "Finite positive LI-String search controls required");
193 LineIntegralNEBResult result;
194 result.path = initial;
195 auto evaluate = [&](const auto& path) {
196 ++result.batchEvaluations;
197 result.evaluations += path.size();
198 return potential(path);
199 };
200 auto state = [&](const auto& path, const auto& values) {
201 return evaluateLineIntegralString(path, values, options.energy,
202 options.spring, options.contour,
203 options.hbar, options.action);
204 };
205 result.native = evaluate(result.path);
206 result.state = state(result.path, result.native);
207 auto force = result.state.force;
208 std::vector<Eigen::VectorXd> velocity(
209 initial.size(), Eigen::VectorXd::Zero(initial.front().size()));
210 double dt = options.timeStep, alpha = options.initialMixing;
211 std::size_t positive = 0;
212 if (fireState && fireState->initialized) {
213 if (fireState->velocity.size() != initial.size() ||
214 !(fireState->timeStep > 0.) ||
215 !std::isfinite(fireState->timeStep) ||
216 !(fireState->mixing >= 0. && fireState->mixing <= 1.) ||
217 !std::isfinite(fireState->mixing))
218 throw std::invalid_argument(
219 "Finite matching LI-String FIRE state required");
220 for (std::size_t j = 0; j < initial.size(); ++j)
221 if (fireState->velocity[j].size() != initial.front().size() ||
222 !fireState->velocity[j].allFinite())
223 throw std::invalid_argument(
224 "Matching finite LI-String FIRE velocities required");
225 velocity = fireState->velocity;
226 dt = std::min(fireState->timeStep, options.maximumTimeStep);
227 if (options.minimumTimeStep > 0.)
228 dt = std::max(dt, options.minimumTimeStep);
229 alpha = fireState->mixing;
230 positive = fireState->positiveSteps;
231 }
232 auto saveFireState = [&] {
233 if (!fireState) return;
234 fireState->velocity = velocity;
235 fireState->timeStep = dt;
236 fireState->mixing = alpha;
237 fireState->positiveSteps = positive;
238 fireState->initialized = true;
239 };
240 for (std::size_t iteration = 0; iteration <= options.maximumIterations;
241 ++iteration) {
242 result.iterations = iteration;
243 if (retain) retain(result);
244 if (result.state.maximumForce < options.forceTolerance &&
245 result.state.endpointEnergyError < options.energyTolerance) {
246 auto equalArc = reparameterizeLineIntegralString(result.path);
247 double redistribution = 0.;
248 double pathScale = 1.;
249 for (std::size_t j = 0; j < equalArc.size(); ++j) {
250 redistribution = std::max(
251 redistribution, (equalArc[j] - result.path[j]).norm());
252 pathScale = std::max(pathScale, result.path[j].norm());
253 }
254 if (redistribution >
255 64. * std::numeric_limits<double>::epsilon() * pathScale) {
256 result.path = std::move(equalArc);
257 result.native = evaluate(result.path);
258 result.state = state(result.path, result.native);
259 force = result.state.force;
260 positive = 0;
261 for (auto& v: velocity)
262 v.setZero();
263 continue;
264 }
265 if (!result.state.turningOrientationsQualified) {
266 result.failure =
267 "LI-String turning orientation does not enter the "
268 "forbidden region";
269 saveFireState();
270 return result;
271 }
272 result.converged = true;
273 saveFireState();
274 return result;
275 }
276 if (iteration == options.maximumIterations) break;
277 std::vector<Eigen::VectorXd> step(initial.size()),
278 trial(initial.size());
279 double largest = 0.;
280 for (std::size_t j = 0; j < trial.size(); ++j) {
281 step[j] = dt * velocity[j] + .5 * dt * dt * force[j];
282 largest = std::max(largest, step[j].norm());
283 }
284 const double scale =
285 largest > options.maximumStep ? options.maximumStep / largest : 1.;
286 double fraction = scale;
287 bool accepted = false, reparameterized = false;
288 std::vector<PotentialEvaluation> next;
289 LineIntegralNEBState nextState;
290 for (int backtrack = 0; backtrack < 24; ++backtrack) {
291 for (std::size_t j = 0; j < trial.size(); ++j)
292 trial[j] = result.path[j] + fraction * step[j];
293 try {
294 const bool needsReparameterization =
296 if (needsReparameterization)
298 next = evaluate(trial);
299 nextState = state(trial, next);
300 reparameterized = needsReparameterization;
301 accepted = true;
302 break;
303 } catch (const std::domain_error&) {
304 fraction *= .5;
305 }
306 }
307 if (!accepted) {
308 result.failure =
309 "No admissible LI-String step in the forbidden region";
310 saveFireState();
311 return result;
312 }
313 auto nextForce = nextState.force;
314 double power = 0., vv = 0., ff = 0.;
315 for (std::size_t j = 0; j < trial.size(); ++j) {
316 velocity[j] += .5 * dt * (force[j] + nextForce[j]);
317 power += velocity[j].dot(nextForce[j]);
318 vv += velocity[j].squaredNorm();
319 ff += nextForce[j].squaredNorm();
320 }
321 if (reparameterized) {
322 positive = 0;
323 alpha = .1;
324 for (auto& v: velocity)
325 v.setZero();
326 } else if (power > 0. && fraction == scale) {
327 ++positive;
328 if (ff > 0.)
329 for (std::size_t j = 0; j < trial.size(); ++j)
330 velocity[j] = (1. - alpha) * velocity[j] +
331 alpha * std::sqrt(vv / ff) * nextForce[j];
332 if (positive > 5) {
333 dt = std::min(dt * 1.1, options.maximumTimeStep);
334 alpha *= .99;
335 }
336 } else {
337 positive = 0;
338 dt = options.minimumTimeStep > 0.
339 ? std::max(options.minimumTimeStep, dt * .5)
340 : dt * .5;
341 alpha = options.initialMixing;
342 for (auto& v: velocity)
343 v.setZero();
344 }
345 result.path = std::move(trial);
346 result.native = std::move(next);
347 result.state = std::move(nextState);
348 force = std::move(nextForce);
349 if (!(dt > std::numeric_limits<double>::epsilon())) {
350 result.failure = "LI-String time step underflows";
351 saveFireState();
352 return result;
353 }
354 }
355 result.failure = "LI-String iteration limit";
356 saveFireState();
357 return result;
358}
std::vector< Eigen::VectorXd > reparameterizeLineIntegralString(const std::vector< Eigen::VectorXd > &path)
LineIntegralNEBState evaluateLineIntegralString(const std::vector< Eigen::VectorXd > &q, const std::vector< PotentialEvaluation > &values, double energy, double spring=1., double contour=10., double hbar=1., LineIntegralAction action=LineIntegralAction::MomentumTrapezoid)
bool lineIntegralStringNeedsReparameterization(const std::vector< Eigen::VectorXd > &path)

◆ optimizePotentialPath() [1/2]

PotentialPathResult gpr::quantum::optimizePotentialPath ( const Nodes & initial,
const MassMetric & metric,
const PathPotential & potential,
const AffinePathBoundary & boundary,
const PathConstraints & constraints,
const PotentialPathOptions & options )

Definition at line 80 of file PotentialPath.cpp.

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)
275 ++result.searchHessianEvaluations;
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 }
295 result.maximumHessianAsymmetry =
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;
343 item.hessianEvaluations = result.hessianEvaluations;
344 item.searchHessianEvaluations = result.searchHessianEvaluations;
345 item.batchEvaluations = result.batchEvaluations;
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;
425 result.fullStationarityQualified =
426 state.fullForce <= options.forceTolerance &&
427 state.constraint <= options.constraintTolerance;
428 result.conditionalStationarityQualified =
429 state.conditionalForce <= options.forceTolerance &&
430 state.constraint <= options.constraintTolerance;
431 result.converged = options.requireFullStationarity
432 ? result.fullStationarityQualified
433 : result.conditionalStationarityQualified;
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}
Eigen::MatrixXd hessian(const Eigen::MatrixXd &physicalHessian) const
Eigen::VectorXd Vector
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)
std::function< Eigen::MatrixXd(const Eigen::VectorXd &)> searchHessian
std::function< Eigen::MatrixXd(const Eigen::VectorXd &)> hessian
ReferenceDiscretization referenceDiscretization

◆ optimizePotentialPath() [2/2]

PotentialPathResult gpr::quantum::optimizePotentialPath ( const std::vector< Eigen::VectorXd > & initial,
const MassMetric & metric,
const PathPotential & potential,
const AffinePathBoundary & boundary,
const PathConstraints & constraints,
const PotentialPathOptions & options = {} )

Uniform cyclic action with trapezoidal physical residual endpoint values. SymmetricResidual integrates a PSD reference kernel; FrequencyFittedKinetic fits the untwisted harmonic trace while preserving stationary wells. Cell and periodic-image semantics belong entirely to the potential callback. Constraint columns are jointly orthonormal over all nodes; empty means none. Returned force residuals are mass-coordinate action gradients divided by dt. No phase volume, determinant or physical rate is inferred from convergence.

◆ optimizeReflectedPotentialPath()

PotentialPathResult gpr::quantum::optimizeReflectedPotentialPath ( const std::vector< Eigen::VectorXd > & initial,
const MassMetric & metric,
const PathPotential & potential,
const PathConstraints & gauge,
const PotentialPathOptions & options = {},
ReflectedSearchCache * retainedSearch = nullptr )
inline

Definition at line 316 of file ReflectedPotentialPath.h.

319 {},
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}
const Eigen::VectorXd & roots() const 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)
Half refined(GaussianProcessRegression &gp, const GradientOracle &oracle, const Eigen::VectorXd &x, Kind kind, const Options &raw_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)

◆ optimizeZeroEnergyGeodesic() [1/2]

ZeroEnergyGeodesicResult gpr::quantum::optimizeZeroEnergyGeodesic ( const Eigen::MatrixXd & positiveWellRoot,
double radius,
const std::vector< Eigen::VectorXd > & initial,
const ZeroEnergyGeodesicPotential & potential,
const ZeroEnergyGeodesicOptions & options = {},
const std::function< void(const ZeroEnergyGeodesicResult &)> & retain = {} )

◆ optimizeZeroEnergyGeodesic() [2/2]

ZeroEnergyGeodesicResult gpr::quantum::optimizeZeroEnergyGeodesic ( const M & omega,
double radius,
const std::vector< V > & initial,
const ZeroEnergyGeodesicPotential & potential,
const ZeroEnergyGeodesicOptions & options,
const std::function< void(const ZeroEnergyGeodesicResult &)> & retain )

Definition at line 298 of file ZeroEnergyGeodesic.cpp.

303{
304 require(bool(potential.evaluate) && bool(potential.searchHessians),
305 "Native geodesic value and search-curvature callbacks required");
306 for (double value:
307 {options.forceTolerance, options.momentumTolerance,
308 options.radiusTolerance, options.meshTolerance,
309 options.energyTolerance, options.maximumStep, options.meshStiffness})
310 require(value > 0 && std::isfinite(value),
311 "Positive finite geodesic search scales required");
312 require(options.maximumBacktracks > 0,
313 "Geodesic line search needs at least one trial");
314 std::size_t evaluations = 0, batches = 0, hessians = 0, proposals = 0,
315 rejectedProposals = 0;
316 auto measure = [&](const std::vector<V>& q, bool* observed = nullptr) {
317 ZeroEnergyGeodesicResult result;
318 result.path = q;
319 result.native = potential.evaluate(q);
320 evaluations += q.size();
321 ++batches;
322 if (observed) *observed = true;
323 result.evaluation = evaluateZeroEnergyGeodesic(
324 omega, radius, q, result.native, options.meshStiffness, {},
325 options.meshWeights);
326 const auto& e = result.evaluation;
327 result.converged = e.tailPointsOutward && e.turningPointsInward &&
328 e.forceResidual <= options.forceTolerance &&
329 e.momentumResidual <= options.momentumTolerance &&
330 e.radiusResidual <= options.radiusTolerance &&
331 e.meshResidual <= options.meshTolerance &&
332 e.turningEnergyResidual <= options.energyTolerance;
333 result.evaluations = evaluations;
334 result.batchEvaluations = batches;
335 result.searchHessianEvaluations = hessians;
336 result.modelProposals = proposals;
337 result.rejectedModelProposals = rejectedProposals;
338 return result;
339 };
340 require(initial.size() >= 3 && initial.front().size() > 0 &&
341 initial.front().allFinite() && radius > 0 &&
342 std::isfinite(radius) && initial.front().norm() > 0,
343 "A finite nonzero initial matching cut is required");
344 auto feasibleInitial = initial;
345 const double initialRadius = feasibleInitial.front().norm();
346 require(
347 std::abs(initialRadius - radius) <= options.maximumStep * (1 + 1e-12),
348 "Initial matching-radius restoration exceeds the native displacement "
349 "bound");
350 feasibleInitial.front() *= radius / initialRadius;
351 auto state = measure(feasibleInitial);
352 if (retain) retain(state);
353 // The merit scales each independent boundary, transverse-force, mesh and
354 // turning-energy equation by its own physical tolerance.
355 for (std::size_t iteration = 0;
356 !state.converged && iteration < options.maximumIterations;
357 ++iteration) {
358 // Momentum and radius have separate physical tolerances. Their merit
359 // uses each trial's tangent frame so a rotated angular residual cannot
360 // acquire the radial constraint's units or tolerance.
361 auto frameNorm = [&](const ZeroEnergyGeodesicResult& point,
362 bool includeTurningEnergy = true) {
363 const auto& q = point.path;
364 const auto& e = point.evaluation;
365 double norm =
366 std::hypot(e.momentumResidual / options.momentumTolerance,
367 e.radiusResidual / options.radiusTolerance);
368 for (std::size_t j = 1; j + 1 < q.size(); ++j) {
369 const V left = (q[j] - q[j - 1]).normalized(),
370 right = (q[j + 1] - q[j]).normalized();
371 const V tangent = options.meshWeights.empty()
372 ? V((left + right).normalized())
373 : meshGeometry(q[j - 1], q[j], q[j + 1],
374 options.meshWeights[j - 1],
375 options.meshWeights[j])
376 .tangent;
377 const double along = e.residual[j].dot(tangent);
378 norm =
379 std::hypot(norm, (e.residual[j] - along * tangent).norm() /
380 options.forceTolerance);
381 norm = std::hypot(norm, along / (options.meshStiffness *
382 options.meshTolerance));
383 }
384 const V chord = q.back() - q[q.size() - 2],
385 tangent = chord.normalized();
386 const double along = e.residual.back().dot(tangent);
387 norm =
388 std::hypot(norm, (e.residual.back() - along * tangent).norm() /
389 options.forceTolerance);
390 return includeTurningEnergy
391 ? std::hypot(norm, along * chord.norm() /
392 options.energyTolerance)
393 : norm;
394 };
395 const double initialFrameNorm = frameNorm(state);
396 const V initialMesh =
397 geodesicMeshConstraints(state.path, options.meshWeights);
398 double trialStepLimit = options.maximumStep;
399 auto attempt = [&](const std::vector<V>& step,
400 std::size_t maximumBacktracks, const V& meshChange,
401 bool returnAfterObservation = false) {
402 double maximum = 0;
403 for (const auto& value: step)
404 maximum = std::max(maximum, value.norm());
405 double scale =
406 maximum > trialStepLimit ? trialStepLimit / maximum : 1.;
407 for (std::size_t trial = 0; trial < maximumBacktracks;
408 ++trial, scale *= .5) {
409 auto q = state.path;
410 for (std::size_t j = 0; j < q.size(); ++j)
411 q[j] += scale * step[j];
412 const double rawRadius = q.front().norm();
413 if (!(rawRadius > 0) || !std::isfinite(rawRadius)) continue;
414 q.front() *= radius / rawRadius;
415 try {
416 q = retractGeodesicMesh(q, options.meshWeights,
417 options.meshTolerance / 16.,
418 initialMesh + scale * meshChange);
419 } catch (const std::domain_error&) {
420 continue;
421 }
422 double displacement = 0;
423 for (std::size_t j = 0; j < q.size(); ++j)
424 displacement =
425 std::max(displacement, (q[j] - state.path[j]).norm());
426 if (displacement > options.maximumStep * (1 + 1e-12)) continue;
427 bool observed = false;
428 try {
429 auto next = measure(q, &observed);
430 if (options.restoreTurningEnergy &&
431 next.evaluation.turningEnergyResidual >
432 options.energyTolerance &&
433 frameNorm(next, false) < initialFrameNorm) {
434 std::vector<ZeroEnergyGeodesicResult> contours;
436 next.path[next.path.size() - 2], next.path.back(),
437 next.native.back(), 0., options.energyTolerance,
438 [&](const V& point) {
439 if ((point - state.path.back()).norm() >
440 options.maximumStep * (1 + 1e-12))
441 throw std::domain_error(
442 "Native contour restoration exceeds "
443 "the displacement bound");
444 auto restored = next.path;
445 restored.back() = point;
446 contours.push_back(measure(restored));
447 return contours.back().native.back();
448 });
449 for (auto& contour: contours) {
450 const auto& e = contour.evaluation;
451 if ((state.evaluation.tailPointsOutward &&
452 !e.tailPointsOutward) ||
453 (state.evaluation.turningPointsInward &&
454 !e.turningPointsInward))
455 continue;
456 if (frameNorm(contour) < frameNorm(next))
457 next = std::move(contour);
458 }
459 }
460 if ((state.evaluation.tailPointsOutward &&
461 !next.evaluation.tailPointsOutward) ||
462 (state.evaluation.turningPointsInward &&
463 !next.evaluation.turningPointsInward)) {
464 if (returnAfterObservation) return false;
465 continue;
466 }
467 if (next.converged || frameNorm(next) < initialFrameNorm) {
468 next.acceptedSteps = state.acceptedSteps + 1;
469 state = std::move(next);
470 if (retain) retain(state);
471 return true;
472 }
473 if (returnAfterObservation) return false;
474 } catch (const std::domain_error&) {
475 if (returnAfterObservation && observed) return false;
476 continue;
477 }
478 }
479 return false;
480 };
481 bool accepted = false;
482 if (potential.propose)
483 for (std::size_t modelTrial = 0; modelTrial < 2 && !accepted;
484 ++modelTrial) {
485 state.evaluations = evaluations;
486 state.batchEvaluations = batches;
487 state.searchHessianEvaluations = hessians;
488 state.modelProposals = proposals;
489 state.rejectedModelProposals = rejectedProposals;
490 const auto proposed = potential.propose(state);
491 if (!proposed.empty()) {
492 require(proposed.size() == state.path.size(),
493 "Geodesic model proposal image count differs");
494 std::vector<V> step;
495 double maximum = 0;
496 for (std::size_t j = 0; j < proposed.size(); ++j) {
497 require(proposed[j].size() == state.path[j].size() &&
498 proposed[j].allFinite(),
499 "Invalid geodesic model proposal metric or "
500 "coordinate");
501 step.push_back(proposed[j] - state.path[j]);
502 maximum = std::max(maximum, step.back().norm());
503 }
504 if (maximum > 0) {
505 ++proposals;
506 try {
507 auto endpoint = proposed;
508 const double endpointRadius =
509 endpoint.front().norm();
510 if (!(endpointRadius > 0) ||
511 !std::isfinite(endpointRadius))
512 throw std::domain_error(
513 "Finite model matching cut required");
514 endpoint.front() *= radius / endpointRadius;
515 const V meshChange =
517 options.meshWeights) -
518 initialMesh;
519 accepted = attempt(step, options.maximumBacktracks,
520 meshChange, true);
521 } catch (const std::domain_error&) {
522 accepted = false;
523 }
524 if (!accepted) {
525 ++rejectedProposals;
526 trialStepLimit =
527 .5 * std::min(trialStepLimit, maximum);
528 }
529 } else
530 break;
531 } else
532 break;
533 }
534 if (!accepted) {
535 trialStepLimit = options.maximumStep;
536 const auto search = potential.searchHessians(state.path);
537 hessians += state.path.size();
538 auto quadratic = evaluateZeroEnergyGeodesic(
539 omega, radius, state.path, state.native, options.meshStiffness,
540 search, options.meshWeights);
541 const auto d = state.path.front().size();
542 const V radial = state.path.front().normalized();
543 const M identity = M::Identity(d, d),
544 projection = identity - radial * radial.transpose();
545 // Parallel transport removes K*r from the Cartesian residual
546 // derivative, where K=dt*t^T-t*dt^T. The resulting Newton equation
547 // decreases the separate physical and mesh residual components.
548 auto transport = [&](M& block, const V& tangent, const V& residual,
549 const M& dt) {
550 const double along = residual.dot(tangent);
551 const V transverse = residual - along * tangent;
552 block += tangent * (transverse.transpose() * dt) - along * dt;
553 };
554 transport(quadratic.diagonal.front(), radial,
555 quadratic.residual.front(),
556 projection / state.path.front().norm());
557 for (std::size_t j = 1; j + 1 < state.path.size(); ++j) {
558 const V previous = state.path[j] - state.path[j - 1],
559 next = state.path[j + 1] - state.path[j];
560 const double a = previous.norm(), b = next.norm();
561 const V u = previous / a, v = next / b, both = u + v;
562 V tangent = both.normalized();
563 MeshGeometry graded;
564 if (!options.meshWeights.empty()) {
565 graded = meshGeometry(
566 state.path[j - 1], state.path[j], state.path[j + 1],
567 options.meshWeights[j - 1], options.meshWeights[j]);
568 tangent = graded.tangent;
569 }
570 const M normal = identity - tangent * tangent.transpose();
571 for (int side = -1; side <= 1; ++side) {
572 const double before = side == -1 ? 1. : 0.,
573 here = side == 0 ? 1. : 0.,
574 after = side == 1 ? 1. : 0.;
575 M dt;
576 if (options.meshWeights.empty()) {
577 const M derivative =
578 (here - before) / a *
579 (identity - u * u.transpose()) +
580 (after - here) / b * (identity - v * v.transpose());
581 dt = (derivative -
582 tangent * (tangent.transpose() * derivative)) /
583 both.norm();
584 } else {
585 const double hm = graded.left, hp = graded.right;
586 const double coefficient = (hp / hm * (here - before) +
587 hm / hp * (after - here)) /
588 (hm + hp);
589 dt = (coefficient / graded.speed) * normal;
590 }
591 M& block = side == -1 ? quadratic.lower[j]
592 : (side == 0 ? quadratic.diagonal[j]
593 : quadratic.upper[j]);
594 transport(block, tangent, quadratic.residual[j], dt);
595 }
596 }
597 const V chord =
598 state.path.back() - state.path[state.path.size() - 2],
599 tangent = chord.normalized();
600 const M turnNormal = identity - tangent * tangent.transpose();
601 transport(quadratic.lower.back(), tangent,
602 quadratic.residual.back(), M(-turnNormal / chord.norm()));
603 transport(quadratic.diagonal.back(), tangent,
604 quadratic.residual.back(), M(turnNormal / chord.norm()));
605 std::vector<V> step;
606 try {
607 step = solveZeroEnergyGeodesicStep(quadratic);
608 } catch (const std::exception& error) {
609 state.failure = error.what();
610 break;
611 }
612 accepted = attempt(step, options.maximumBacktracks, -initialMesh);
613 }
614 if (!accepted) {
615 state.failure =
616 "Native geodesic residual does not decrease along the search "
617 "step";
618 break;
619 }
620 }
621 if (!state.converged && state.failure.empty())
622 state.failure = "Maximum native geodesic iterations reached";
623 state.evaluations = evaluations;
624 state.batchEvaluations = batches;
625 state.searchHessianEvaluations = hessians;
626 state.modelProposals = proposals;
627 state.rejectedModelProposals = rejectedProposals;
628 return state;
629}
std::vector< Eigen::VectorXd > retractGeodesicMesh(const std::vector< Eigen::VectorXd > &path, const std::vector< double > &weights, double tolerance, const Eigen::VectorXd &target={})
SphereEnergyProjection projectSphereEnergy(const Eigen::VectorXd &center, const Eigen::VectorXd &point, const PotentialEvaluation &value, double energy, double tolerance, const Evaluate &evaluate, std::size_t maximumIterations=8, std::size_t maximumBacktracks=12)
std::vector< V > solveZeroEnergyGeodesicStep(const ZeroEnergyGeodesicEvaluation &state)
Eigen::VectorXd geodesicMeshConstraints(const std::vector< Eigen::VectorXd > &path, const std::vector< double > &weights={})
std::function< std::vector< Eigen::MatrixXd >(const std::vector< Eigen::VectorXd > &)> searchHessians
std::function< std::vector< PotentialEvaluation >(const std::vector< Eigen::VectorXd > &)> evaluate
std::function< std::vector< Eigen::VectorXd >(const ZeroEnergyGeodesicResult &)> propose

◆ phasePlaneJacobian()

double gpr::quantum::phasePlaneJacobian ( const Eigen::VectorXd & unitNormal,
const Eigen::VectorXd & normalDerivative,
double targetDerivative,
const Eigen::VectorXd & point )

Coarea Jacobian for a moving unit plane n(theta)^T q=c(theta). The returned value is abs(c' - dot(n', q)), not the speed along a curved conditional family. A zero value is a singular phase chart.

Definition at line 11 of file SaddleFamilyRate.cpp.

14{
15 if (!normal.size() || derivative.size() != normal.size() ||
16 point.size() != normal.size() || !normal.allFinite() ||
17 !derivative.allFinite() || !point.allFinite() ||
18 !std::isfinite(targetDerivative) ||
19 std::abs(normal.squaredNorm() - 1) > 1e-12 ||
20 std::abs(normal.dot(derivative)) >
21 1e-12 * std::max(1., derivative.norm()))
22 throw std::invalid_argument(
23 "Finite matching unit phase plane and tangent derivative required");
24 const double jacobian = std::abs(targetDerivative - derivative.dot(point));
25 if (!(jacobian > 0) || !std::isfinite(jacobian))
26 throw std::domain_error(
27 "Phase plane does not define a resolved regular chart");
28 return jacobian;
29}

◆ physicalPathBoundary()

AffinePathBoundary gpr::quantum::physicalPathBoundary ( const MassMetric & m,
const Matrix & linear,
const Vector & translation )

Definition at line 58 of file PotentialPath.cpp.

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}
const Eigen::VectorXd & origin() const noexcept

◆ prepareArcTailForceGradient()

template<class Action>
ArcTailForceGradientData gpr::quantum::prepareArcTailForceGradient ( const Action & action,
const std::vector< Eigen::VectorXd > & points,
double duration,
const std::vector< PotentialEvaluation > & native,
const ArcTailPotential & potential,
const ArcTailSearchOptions & options,
const std::function< std::vector< PotentialEvaluation >(const std::vector< Eigen::VectorXd > &)> & ownedEvaluate )
inline

Definition at line 51 of file ArcTailForceGradient.h.

57{
58 using namespace arc_force_gradient_detail;
60 if constexpr (requires { action.positiveQuadrature(); })
61 if (action.positiveQuadrature() && options.referenceForceGradient)
62 throw std::invalid_argument(
63 "Positive primitive quadrature requires a separately specified "
64 "force-gradient scheme");
65 if (!options.referenceForceGradient) return data;
66 const auto &well = action.wellCurvature();
67 const auto dimension = well.rows();
68 if (points.size() != action.arcWeights().size() + 1 ||
69 !(duration > 0 && duration < action.period()) ||
70 !std::isfinite(duration))
71 throw std::invalid_argument(
72 "Matching arc nodes and finite duration required");
73 requireValues(points, native, dimension);
74 data.enabled = true;
75 data.duration = duration;
76 data.coordinates = points;
77 data.residualGradients.reserve(points.size());
78 data.residualResponses.assign(points.size(), V::Zero(dimension));
79 for (std::size_t j = 0; j < points.size(); ++j) {
80 const V residual = native[j].gradient - well * points[j];
81 if (!residual.allFinite())
82 throw std::overflow_error("Nonfinite native residual gradient");
83 data.residualGradients.push_back(residual);
84 }
85 if (potential.physicalHessianActions) {
86 const auto response =
87 potential.physicalHessianActions(points, data.residualGradients);
88 if (response.size() != points.size())
89 throw std::invalid_argument(
90 "Physical Hessian-action batch shape differs");
91 for (std::size_t j = 0; j < points.size(); ++j) {
92 if (response[j].size() != dimension || !response[j].allFinite())
93 throw std::invalid_argument(
94 "Finite matching physical Hessian actions required");
95 data.residualResponses[j] =
96 response[j] - well * data.residualGradients[j];
97 if (!data.residualResponses[j].allFinite())
98 throw std::overflow_error(
99 "Nonfinite physical residual Hessian action");
100 }
101 data.physicalHessianActionRequests = points.size();
102 return data;
103 }
104 if (!ownedEvaluate || !(options.physicalHessianStep > 0) ||
105 !std::isfinite(options.physicalHessianStep) ||
106 options.maximumHessianRefinements == 0 ||
107 !(options.forceTolerance > 0) || !std::isfinite(options.forceTolerance))
108 throw std::invalid_argument(
109 "Owned native differences need positive finite scales");
110
111 std::vector<std::size_t> active;
112 std::vector<double> norms(points.size(), 0.);
113 for (std::size_t j = 0; j < points.size(); ++j) {
114 norms[j] = data.residualGradients[j].norm();
115 if (!std::isfinite(norms[j]))
116 throw std::overflow_error("Nonfinite residual-gradient norm");
117 if (norms[j] > 0) active.push_back(j);
118 }
119 if (active.empty()) return data;
120 data.usedFiniteDifferences = true;
121 auto difference = [&](double step) {
122 std::vector<V> probes;
123 probes.reserve(2 * active.size());
124 for (const auto j: active) {
125 const V displacement = step * data.residualGradients[j] / norms[j];
126 probes.push_back(points[j] + displacement);
127 probes.push_back(points[j] - displacement);
128 }
129 const auto measured = ownedEvaluate(probes);
130 requireValues(probes, measured, dimension);
131 std::vector<V> response(points.size(), V::Zero(dimension));
132 for (std::size_t slot = 0; slot < active.size(); ++slot) {
133 const auto j = active[slot];
134 response[j] = norms[j] *
135 (measured[2 * slot].gradient -
136 measured[2 * slot + 1].gradient) /
137 (2 * step) -
138 well * data.residualGradients[j];
139 if (!response[j].allFinite())
140 throw std::overflow_error(
141 "Nonfinite native Hessian difference");
142 }
143 data.physicalHessianActionRequests += active.size();
144 return response;
145 };
146 double step = options.physicalHessianStep;
147 auto coarse = difference(step);
148 for (std::size_t refinement = 0;
149 refinement < options.maximumHessianRefinements; ++refinement) {
150 step *= .5;
151 const auto fine = difference(step);
152 data.maximumForceDifference = 0.;
153 for (const auto j: active) {
154 const V correction = (fine[j] - coarse[j]) / 3.;
155 data.residualResponses[j] = fine[j] + correction;
156 if (!data.residualResponses[j].allFinite() ||
157 !correction.allFinite())
158 throw std::overflow_error(
159 "Nonfinite extrapolated native Hessian action");
160 const double h = effectiveStep(action, j, duration);
161 data.maximumForceDifference = std::max(
162 data.maximumForceDifference, h * h * correction.norm() / 12.);
163 }
164 if (data.maximumForceDifference <= .1 * options.forceTolerance)
165 return data;
166 coarse = fine;
167 }
168 throw std::runtime_error(
169 "Native residual Hessian action is unresolved at the force tolerance");
170}

◆ projectReflectionEvenBand()

double gpr::quantum::projectReflectionEvenBand ( std::vector< Eigen::VectorXd > & path)
inline

Definition at line 88 of file ReflectionEvenBand.h.

89{
90 if (path.size() < 3 || path.size() % 2 == 0)
91 throw std::invalid_argument(
92 "An odd closed band is required for reflection projection");
93 const auto d = path.front().size();
94 for (const auto& point: path)
95 if (d == 0 || point.size() != d || !point.allFinite())
96 throw std::invalid_argument(
97 "Matching finite reflection coordinates required");
98 double correction = 0;
99 for (std::size_t j = 0; j < path.size() / 2; ++j) {
100 const auto k = path.size() - 1 - j;
101 const Eigen::VectorXd average = .5 * path[j] + .5 * path[k];
102 correction = std::max({correction, (average - path[j]).stableNorm(),
103 (average - path[k]).stableNorm()});
104 if (!std::isfinite(correction))
105 throw std::overflow_error(
106 "Reflection correction exceeds arithmetic range");
107 path[j] = average;
108 path[k] = average;
109 }
110 return correction;
111}

◆ projectSphereEnergy()

template<class Evaluate>
SphereEnergyProjection gpr::quantum::projectSphereEnergy ( const Eigen::VectorXd & center,
const Eigen::VectorXd & point,
const PotentialEvaluation & value,
double energy,
double tolerance,
const Evaluate & evaluate,
std::size_t maximumIterations = 8,
std::size_t maximumBacktracks = 12 )

Definition at line 25 of file SphereEnergyProjection.h.

32{
33 using V = Eigen::VectorXd;
34 const auto d = point.size();
35 auto valid = [&](const PotentialEvaluation& v) {
36 return std::isfinite(v.energy) && v.gradient.size() == d &&
37 v.gradient.allFinite();
38 };
39 if (d == 0 || center.size() != d || !point.allFinite() ||
40 !center.allFinite() || !valid(value) || !std::isfinite(energy) ||
41 !(tolerance > 0) || !std::isfinite(tolerance) || maximumBacktracks == 0)
42 throw std::invalid_argument(
43 "Finite sphere coordinates, native gradient and positive energy "
44 "tolerance required");
45 const double length = (point - center).norm();
46 if (!(length > 0) || !std::isfinite(length))
47 throw std::invalid_argument(
48 "A resolved final geodesic link is required");
49 SphereEnergyProjection result{point, value, 0,
50 std::abs(value.energy - energy) <= tolerance};
51 for (std::size_t iteration = 0;
52 !result.converged && iteration < maximumIterations; ++iteration) {
53 const V radius = result.point - center, tangent = radius.normalized();
54 const V normal = result.value.gradient -
55 tangent.dot(result.value.gradient) * tangent;
56 const double squared = normal.squaredNorm();
57 const double eps = std::numeric_limits<double>::epsilon();
58 if (!(squared > eps * eps * result.value.gradient.squaredNorm()))
59 return result;
60 const V step = -(result.value.energy - energy) / squared * normal;
61 if (!step.allFinite()) return result;
62 bool accepted = false;
63 double scale = 1.;
64 for (std::size_t backtrack = 0; backtrack < maximumBacktracks;
65 ++backtrack, scale *= .5) {
66 const V raw = radius + scale * step;
67 if (!(raw.norm() > 0) || !raw.allFinite()) continue;
68 const V trial = center + length * raw.normalized();
69 if ((trial.array() == result.point.array()).all()) continue;
70 PotentialEvaluation measured;
71 try {
72 ++result.evaluations;
73 measured = evaluate(trial);
74 } catch (const std::domain_error&) {
75 continue;
76 }
77 if (!valid(measured))
78 throw std::runtime_error(
79 "Sphere projection received invalid native values");
80 if (std::abs(measured.energy - energy) <
81 std::abs(result.value.energy - energy)) {
82 result.point = trial;
83 result.value = std::move(measured);
84 result.converged =
85 std::abs(result.value.energy - energy) <= tolerance;
86 accepted = true;
87 break;
88 }
89 }
90 if (!accepted) return result;
91 }
92 return result;
93}

◆ quadraticArcActionChange()

double gpr::quantum::quadraticArcActionChange ( const ArcTailEvaluation & state,
const std::vector< Eigen::VectorXd > & displacement )
inline

Definition at line 98 of file IndexTargetedArc.h.

101{
102 if (displacement.size() != state.gradient.size() ||
103 displacement.size() != state.fluctuationSegments.size())
104 throw std::invalid_argument(
105 "Matching arc quadratic displacement required");
106 double result = 0;
107 for (std::size_t j = 0; j < displacement.size(); ++j) {
108 const auto next = (j + 1) % displacement.size();
109 const auto& link = state.fluctuationSegments[j];
110 result += state.gradient[j].dot(displacement[j]) +
111 .5 * displacement[j].dot(link.A * displacement[j]) +
112 .5 * displacement[next].dot(link.rightEndpoint() *
113 displacement[next]) -
114 displacement[j].dot(link.L * displacement[next]);
115 }
116 return result;
117}
std::vector< Eigen::VectorXd > gradient
std::vector< gpr::quantum::gaussian::Segment > fluctuationSegments

◆ reducedGaussianGLERestrictedTrace()

gaussian::TwistedRestrictedResult gpr::quantum::reducedGaussianGLERestrictedTrace ( const ReducedGaussianGLEResult & reduced,
const Eigen::VectorXd & phaseNormal,
double duration,
double unresolvedTolerance = 1e-12 )
inline

Definition at line 587 of file ReducedGaussianGLE.h.

590{
591 const Eigen::Index fullDimension = reduced.effectiveHessian.rows();
592 if (fullDimension < 2 || reduced.effectiveHessian.cols() != fullDimension ||
593 phaseNormal.size() != fullDimension || !phaseNormal.allFinite() ||
594 std::abs(phaseNormal.squaredNorm() - 1.) > 1e-12 || !(duration > 0.) ||
595 !std::isfinite(duration) || !(unresolvedTolerance >= 0.) ||
596 !std::isfinite(unresolvedTolerance))
597 throw std::invalid_argument(
598 "Finite reduced Gaussian ring and unit phase normal required");
599 Eigen::HouseholderQR<Eigen::MatrixXd> qr(phaseNormal);
600 Eigen::MatrixXd orthogonal =
601 qr.householderQ() *
602 Eigen::MatrixXd::Identity(fullDimension, fullDimension);
603 const Eigen::MatrixXd tangent = orthogonal.rightCols(fullDimension - 1);
604 const Eigen::MatrixXd restricted =
605 tangent.transpose() * reduced.effectiveHessian * tangent;
606 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigen(
607 restricted, Eigen::EigenvaluesOnly);
608 if (eigen.info() != Eigen::Success || !eigen.eigenvalues().allFinite())
609 throw std::runtime_error(
610 "Reduced restricted Gaussian eigensolve failed");
612 trace.dimension = fullDimension - 1;
613 trace.codimension = 1;
614 trace.duration = duration;
615 double logAbs = 0.;
616 const double scale =
617 std::max(1., eigen.eigenvalues().cwiseAbs().maxCoeff());
618 for (double value: eigen.eigenvalues()) {
619 if (std::abs(value) <= unresolvedTolerance * scale) {
621 } else {
622 if (value > 0.)
623 ++trace.inertia.positive;
624 else
625 ++trace.inertia.negative;
626 logAbs += std::log(std::abs(value));
627 }
628 }
629 if (!trace.unresolvedBorderEigenvalues) trace.logAbsNormalizedDet = logAbs;
630 return trace;
631}

◆ reducedGaussianGLETrace()

gaussian::TwistedTraceResult gpr::quantum::reducedGaussianGLETrace ( const ReducedGaussianGLEResult & reduced,
double duration,
double unresolvedTolerance = 1e-12 )
inline

Definition at line 549 of file ReducedGaussianGLE.h.

552{
553 const Eigen::Index dimension = reduced.effectiveHessian.rows();
554 if (dimension <= 0 || reduced.effectiveHessian.cols() != dimension ||
555 !(duration > 0.) || !std::isfinite(duration) ||
556 !(unresolvedTolerance >= 0.) || !std::isfinite(unresolvedTolerance))
557 throw std::invalid_argument(
558 "Finite reduced Gaussian trace and duration required");
559 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigen(
560 reduced.effectiveHessian, Eigen::EigenvaluesOnly);
561 if (eigen.info() != Eigen::Success || !eigen.eigenvalues().allFinite())
562 throw std::runtime_error("Reduced Gaussian trace eigensolve failed");
564 trace.dimension = dimension;
565 trace.duration = duration;
566 for (double value: eigen.eigenvalues()) {
567 if (std::abs(value) <=
568 unresolvedTolerance *
569 std::max(1., eigen.eigenvalues().cwiseAbs().maxCoeff())) {
571 ++trace.inertia.zero;
572 } else {
573 if (value > 0.)
574 ++trace.inertia.positive;
575 else
576 ++trace.inertia.negative;
577 }
578 }
579 if (!trace.unresolvedSchurEigenvalues && !trace.inertia.negative)
581 return trace;
582}

◆ reducedGaussianSegmentGLERestrictedTrace()

gaussian::TwistedRestrictedResult gpr::quantum::reducedGaussianSegmentGLERestrictedTrace ( const ReducedGaussianSegmentResult & reduced,
const Eigen::VectorXd & phaseNormal,
double unresolvedTolerance = 1e-12 )
inline

Definition at line 215 of file ReducedGaussianGLE.h.

218{
219 using Index = Eigen::Index;
220 const Index full = reduced.fullDimension;
221 const Index activeTotal = reduced.effectiveHessian.rows();
222 if (full <= 1 || activeTotal <= 1 || reduced.activeDimension <= 0 ||
223 reduced.beads < 3 ||
224 reduced.physicalDimension <= reduced.activeDimension ||
225 reduced.activeBasis.rows() != reduced.physicalDimension ||
226 reduced.activeBasis.cols() != reduced.activeDimension ||
227 phaseNormal.size() != full || !phaseNormal.allFinite() ||
228 std::abs(phaseNormal.squaredNorm() - 1.) > 1e-12 ||
229 !(reduced.duration > 0.) || !(unresolvedTolerance >= 0.) ||
230 !std::isfinite(unresolvedTolerance))
231 throw std::invalid_argument(
232 "A unit full-path phase normal and finite reduced result are "
233 "required");
234 if (reduced.beads * reduced.activeDimension != activeTotal ||
235 reduced.beads * reduced.physicalDimension != full ||
236 reduced.bathDimension != reduced.beads * (reduced.physicalDimension -
237 reduced.activeDimension))
238 throw std::invalid_argument(
239 "Reduced active and full-path dimensions differ");
240 Eigen::VectorXd activeNormal(activeTotal);
241 double discardedNorm = 0.;
242 for (Index bead = 0; bead < reduced.beads; ++bead) {
243 const auto fullBlock = phaseNormal.segment(
244 bead * reduced.physicalDimension, reduced.physicalDimension);
245 activeNormal.segment(bead * reduced.activeDimension,
246 reduced.activeDimension) =
247 reduced.activeBasis.transpose() * fullBlock;
248 discardedNorm += (fullBlock - reduced.activeBasis *
249 activeNormal.segment(
250 bead * reduced.activeDimension,
251 reduced.activeDimension))
252 .squaredNorm();
253 }
254 if (discardedNorm > 1e-20 ||
255 std::abs(activeNormal.squaredNorm() - 1.) > 1e-12)
256 throw std::invalid_argument(
257 "The phase normal must lie in the retained active subspace");
258 Eigen::HouseholderQR<Eigen::MatrixXd> qr(activeNormal);
259 const Eigen::MatrixXd q =
260 qr.householderQ() * Eigen::MatrixXd::Identity(activeTotal, activeTotal);
261 const Eigen::MatrixXd tangent = q.rightCols(activeTotal - 1);
262 const Eigen::MatrixXd restricted =
263 tangent.transpose() * reduced.effectiveHessian * tangent;
264 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigen(
265 restricted, Eigen::EigenvaluesOnly);
266 if (eigen.info() != Eigen::Success || !eigen.eigenvalues().allFinite())
267 throw std::runtime_error(
268 "Finite-path restricted Gaussian eigensolve failed");
269 gaussian::TwistedRestrictedResult trace;
270 trace.dimension = activeTotal - 1 + reduced.bathDimension;
271 trace.codimension = 1;
272 trace.duration = reduced.duration;
273 const double scale =
274 std::max(1., eigen.eigenvalues().cwiseAbs().maxCoeff());
275 double logAbs =
277 trace.inertia.positive = static_cast<std::size_t>(reduced.bathDimension);
278 for (double value: eigen.eigenvalues()) {
279 if (std::abs(value) <= unresolvedTolerance * scale)
280 ++trace.unresolvedBorderEigenvalues;
281 else {
282 if (value > 0.)
283 ++trace.inertia.positive;
284 else
285 ++trace.inertia.negative;
286 logAbs += std::log(std::abs(value));
287 }
288 }
289 if (!trace.unresolvedBorderEigenvalues) trace.logAbsNormalizedDet = logAbs;
290 return trace;
291}

◆ reducedGaussianSegmentGLETrace()

gaussian::TwistedTraceResult gpr::quantum::reducedGaussianSegmentGLETrace ( const ReducedGaussianSegmentResult & reduced)
inline

Definition at line 189 of file ReducedGaussianGLE.h.

191{
192 if (reduced.fullDimension <= 0 || reduced.bathDimension <= 0 ||
193 reduced.activeDimension <= 0 || reduced.effectiveHessian.rows() <= 0 ||
194 reduced.effectiveHessian.rows() != reduced.effectiveHessian.cols() ||
195 !(reduced.duration > 0.) || !std::isfinite(reduced.duration))
196 throw std::invalid_argument(
197 "A finite reduced Gaussian segment result is required");
199 trace.dimension = reduced.fullDimension;
200 trace.duration = reduced.duration;
201 trace.inertia.positive = static_cast<std::size_t>(
202 reduced.bathDimension + reduced.effectiveHessian.rows() -
203 reduced.effectiveNegative - reduced.effectiveUnresolved);
204 trace.inertia.negative =
205 static_cast<std::size_t>(reduced.effectiveNegative);
206 trace.inertia.zero = static_cast<std::size_t>(reduced.effectiveUnresolved);
207 if (!trace.inertia.zero)
211 return trace;
212}

◆ reduceGaussianSegmentsGLE()

ReducedGaussianSegmentResult gpr::quantum::reduceGaussianSegmentsGLE ( const std::vector< gaussian::Segment > & segments,
const Eigen::MatrixXd & activeBasis,
double unresolvedTolerance = 1e-12 )
inline

Definition at line 55 of file ReducedGaussianGLE.h.

58{
59 using Matrix = Eigen::MatrixXd;
60 using Index = Eigen::Index;
61 const Index beads = static_cast<Index>(segments.size());
62 const Index physical = activeBasis.rows(), active = activeBasis.cols();
63 if (beads < 3 || physical <= 1 || active <= 0 || active >= physical ||
64 !activeBasis.allFinite() ||
65 (activeBasis.transpose() * activeBasis -
66 Matrix::Identity(active, active))
67 .norm() > 1e-10 ||
68 !(unresolvedTolerance >= 0.) || !std::isfinite(unresolvedTolerance))
69 throw std::invalid_argument(
70 "Finite links and an orthonormal proper active subspace are "
71 "required");
72 const Index bath = physical - active, activeTotal = beads * active,
73 bathTotal = beads * bath;
74 if (beads > std::numeric_limits<Index>::max() / physical ||
75 beads * physical > 16384 || bathTotal > 8192)
76 throw std::length_error(
77 "Finite Gaussian segment reduction exceeds its dense factorization "
78 "limit");
79 Eigen::HouseholderQR<Matrix> qr(activeBasis);
80 const Matrix orthogonal =
81 qr.householderQ() * Matrix::Identity(physical, physical);
82 const Matrix bathBasis = orthogonal.rightCols(bath);
83 Matrix aa = Matrix::Zero(activeTotal, activeTotal);
84 Matrix ab = Matrix::Zero(activeTotal, bathTotal);
85 Matrix bb = Matrix::Zero(bathTotal, bathTotal);
86 double duration = 0., linkNormalization = 0.;
87 for (Index i = 0; i < beads; ++i) {
88 const auto& link = segments[static_cast<std::size_t>(i)];
89 const Index j = (i + 1) % beads;
90 const auto& right = link.rightEndpoint();
91 if (link.A.rows() != physical || link.A.cols() != physical ||
92 right.rows() != physical || right.cols() != physical ||
93 link.L.rows() != physical || link.L.cols() != physical ||
94 !link.A.allFinite() || !right.allFinite() || !link.L.allFinite() ||
95 !std::isfinite(link.logDetL) || !(link.duration > 0.) ||
96 !std::isfinite(link.duration))
97 throw std::invalid_argument(
98 "Gaussian links must match the active-space physical "
99 "dimension");
100 const Matrix aaLeft = activeBasis.transpose() * link.A * activeBasis;
101 const Matrix aaRight = activeBasis.transpose() * right * activeBasis;
102 const Matrix aaCross = activeBasis.transpose() * link.L * activeBasis;
103 const Matrix abLeft = activeBasis.transpose() * link.A * bathBasis;
104 const Matrix abRight = activeBasis.transpose() * right * bathBasis;
105 const Matrix abCross = activeBasis.transpose() * link.L * bathBasis;
106 const Matrix baCross =
107 activeBasis.transpose() * link.L.transpose() * bathBasis;
108 const Matrix bbLeft = bathBasis.transpose() * link.A * bathBasis;
109 const Matrix bbRight = bathBasis.transpose() * right * bathBasis;
110 const Matrix bbCross = bathBasis.transpose() * link.L * bathBasis;
111 aa.block(i * active, i * active, active, active) += aaLeft;
112 aa.block(j * active, j * active, active, active) += aaRight;
113 aa.block(i * active, j * active, active, active) -= aaCross;
114 aa.block(j * active, i * active, active, active) -= aaCross.transpose();
115 ab.block(i * active, i * bath, active, bath) += abLeft;
116 ab.block(j * active, j * bath, active, bath) += abRight;
117 ab.block(i * active, j * bath, active, bath) -= abCross;
118 ab.block(j * active, i * bath, active, bath) -= baCross;
119 bb.block(i * bath, i * bath, bath, bath) += bbLeft;
120 bb.block(j * bath, j * bath, bath, bath) += bbRight;
121 bb.block(i * bath, j * bath, bath, bath) -= bbCross;
122 bb.block(j * bath, i * bath, bath, bath) -= bbCross.transpose();
123 duration += link.duration;
124 linkNormalization += link.logDetL;
125 }
126 const double symmetryTolerance = 128 *
127 std::numeric_limits<double>::epsilon() *
128 std::max({1., aa.norm(), bb.norm()});
129 if (!aa.allFinite() || !ab.allFinite() || !bb.allFinite() ||
130 (aa - aa.transpose()).norm() > symmetryTolerance ||
131 (bb - bb.transpose()).norm() > symmetryTolerance ||
132 !std::isfinite(duration) || !std::isfinite(linkNormalization))
133 throw std::runtime_error(
134 "Assembled Gaussian segment blocks are not finite and symmetric");
135 aa = (.5 * aa + .5 * aa.transpose()).eval();
136 bb = (.5 * bb + .5 * bb.transpose()).eval();
137 Eigen::LLT<Matrix> bathFactor(bb);
138 if (bathFactor.info() != Eigen::Success)
139 throw std::domain_error(
140 "The finite-path eliminated Gaussian bath is not positive "
141 "definite");
142 const Matrix diagonal = bathFactor.matrixL().toDenseMatrix().diagonal();
143 const double scale = std::max(1., bb.cwiseAbs().maxCoeff());
144 if ((diagonal.array() <= std::sqrt(unresolvedTolerance * scale)).any())
145 throw std::domain_error(
146 "The finite-path eliminated Gaussian bath is unresolved");
147 const double bathLog = 2. * diagonal.array().log().sum();
148 const Matrix response = bathFactor.solve(ab.transpose());
149 if (bathFactor.info() != Eigen::Success || !response.allFinite())
150 throw std::runtime_error("Finite-path bath response solve failed");
151 Matrix effective = aa - ab * response;
152 if (!effective.allFinite() ||
153 (effective - effective.transpose()).norm() > symmetryTolerance)
154 throw std::runtime_error(
155 "Finite-path reduced Gaussian exceeds symmetry tolerance");
156 effective = (.5 * effective + .5 * effective.transpose()).eval();
157 Eigen::SelfAdjointEigenSolver<Matrix> eigen(effective,
158 Eigen::EigenvaluesOnly);
159 if (eigen.info() != Eigen::Success || !eigen.eigenvalues().allFinite())
160 throw std::runtime_error(
161 "Finite-path reduced Gaussian eigensolve failed");
162 const double effectiveScale =
163 std::max(1., eigen.eigenvalues().cwiseAbs().maxCoeff());
164 double effectiveLog = 0.;
165 Index negative = 0, unresolved = 0;
166 for (double value: eigen.eigenvalues()) {
167 if (std::abs(value) <= unresolvedTolerance * effectiveScale)
168 ++unresolved;
169 else {
170 negative += value < 0.;
171 effectiveLog += std::log(std::abs(value));
172 }
173 }
174 return {std::move(effective),
175 activeBasis,
176 bathLog,
177 effectiveLog,
178 linkNormalization,
179 bathTotal,
180 active,
181 beads * physical,
182 negative,
183 unresolved,
184 beads,
185 physical,
186 duration};
187}

◆ reducePeriodicGaussianGLE() [1/2]

ReducedGaussianGLEResult gpr::quantum::reducePeriodicGaussianGLE ( const std::vector< Eigen::MatrixXd > & activeHessians,
const Eigen::MatrixXd & coupling,
const Eigen::MatrixXd & bathCurvature,
const Eigen::MatrixXd & activeKineticLink,
const Eigen::MatrixXd & activeBathKineticLink,
const Eigen::MatrixXd & bathKineticLink,
double step,
double unresolvedTolerance = 1e-12 )
inline

Definition at line 422 of file ReducedGaussianGLE.h.

429{
430 using Matrix = Eigen::MatrixXd;
431 using Index = Eigen::Index;
432 const Index beads = static_cast<Index>(activeHessians.size());
433 const Index active = coupling.rows(), bath = coupling.cols();
434 auto symmetric = [](const Matrix& matrix) {
435 return (matrix - matrix.transpose()).norm() <=
436 1e-12 * std::max(1., matrix.norm());
437 };
438 if (beads < 3 || active <= 0 || bath <= 0 || bathCurvature.rows() != bath ||
439 bathCurvature.cols() != bath || activeKineticLink.rows() != active ||
440 activeKineticLink.cols() != active ||
441 activeBathKineticLink.rows() != active ||
442 activeBathKineticLink.cols() != bath ||
443 bathKineticLink.rows() != bath || bathKineticLink.cols() != bath ||
444 !coupling.allFinite() || !bathCurvature.allFinite() ||
445 !activeKineticLink.allFinite() || !activeBathKineticLink.allFinite() ||
446 !bathKineticLink.allFinite() || !symmetric(bathCurvature) ||
447 !symmetric(activeKineticLink) || !symmetric(bathKineticLink) ||
448 !(step > 0.) || !std::isfinite(step) || !(unresolvedTolerance >= 0.) ||
449 !std::isfinite(unresolvedTolerance))
450 throw std::invalid_argument(
451 "Finite periodic active, bath and kinetic blocks are required");
452 for (const auto& hessian: activeHessians)
453 if (hessian.rows() != active || hessian.cols() != active ||
454 !hessian.allFinite() || !symmetric(hessian))
455 throw std::invalid_argument(
456 "Matching finite symmetric active curvatures are required");
457
458 const Index dimension = beads * active;
459 Matrix effective = Matrix::Zero(dimension, dimension);
460 std::vector<Matrix> schurModes;
461 schurModes.reserve(static_cast<std::size_t>(beads));
462 double bathLogAbs = 0.;
463 for (Index mode = 0; mode < beads; ++mode) {
464 const double angle = 2. * std::acos(-1.) * mode / beads;
465 const double ell = 2. * (1. - std::cos(angle));
466 const Matrix bathBlock = step * bathCurvature + ell * bathKineticLink;
467 Eigen::LLT<Matrix> factor(bathBlock);
468 if (factor.info() != Eigen::Success)
469 throw std::domain_error(
470 "Frequency-mode Gaussian GLE bath is not positive definite");
471 const Matrix diagonal = factor.matrixL().toDenseMatrix();
472 const double scale = std::max(1., bathBlock.cwiseAbs().maxCoeff());
473 if ((diagonal.diagonal().array() <=
474 std::sqrt(unresolvedTolerance * scale))
475 .any())
476 throw std::domain_error(
477 "Frequency-mode Gaussian GLE bath is unresolved");
478 bathLogAbs += 2. * diagonal.diagonal().array().log().sum();
479 const Matrix cross = step * coupling + ell * activeBathKineticLink;
480 const Matrix response = factor.solve(cross.transpose());
481 if (factor.info() != Eigen::Success || !response.allFinite())
482 throw std::runtime_error(
483 "Frequency-mode Gaussian GLE bath solve failed");
484 schurModes.push_back(cross * response);
485 }
486
487 for (Index bead = 0; bead < beads; ++bead) {
488 const Index next = (bead + 1) % beads;
489 effective.block(bead * active, bead * active, active, active) +=
490 step * activeHessians[static_cast<std::size_t>(bead)] +
491 2. * activeKineticLink;
492 effective.block(bead * active, next * active, active, active) -=
493 activeKineticLink;
494 effective.block(next * active, bead * active, active, active) -=
495 activeKineticLink.transpose();
496 }
497 for (Index i = 0; i < beads; ++i)
498 for (Index j = 0; j < beads; ++j) {
499 const Index separation = (j - i + beads) % beads;
500 Matrix block = Matrix::Zero(active, active);
501 for (Index mode = 0; mode < beads; ++mode)
502 block.noalias() +=
503 std::cos(2. * std::acos(-1.) * mode * separation / beads) *
504 schurModes[static_cast<std::size_t>(mode)];
505 effective.block(i * active, j * active, active, active) -=
506 block / static_cast<double>(beads);
507 }
508 const double symmetryTolerance = 128. *
509 std::numeric_limits<double>::epsilon() *
510 std::max(1., effective.norm());
511 if (!effective.allFinite() ||
512 (effective - effective.transpose()).norm() > symmetryTolerance)
513 throw std::runtime_error(
514 "Reduced frequency-fitted GLE precision exceeds symmetry "
515 "tolerance");
516 effective = (.5 * effective + .5 * effective.transpose()).eval();
517 Eigen::SelfAdjointEigenSolver<Matrix> eigen(effective,
518 Eigen::EigenvaluesOnly);
519 if (eigen.info() != Eigen::Success || !eigen.eigenvalues().allFinite())
520 throw std::runtime_error(
521 "Reduced frequency-fitted GLE eigensolve failed");
522 const double scale =
523 std::max(1., eigen.eigenvalues().cwiseAbs().maxCoeff());
524 Index negative = 0, unresolved = 0;
525 double effectiveLogAbs = 0.;
526 for (const double value: eigen.eigenvalues()) {
527 if (std::abs(value) <= unresolvedTolerance * scale)
528 ++unresolved;
529 else {
530 negative += value < 0.;
531 effectiveLogAbs += std::log(std::abs(value));
532 }
533 }
534 return {std::move(effective),
535 bathLogAbs,
536 effectiveLogAbs,
537 bathLogAbs + effectiveLogAbs,
538 0,
539 negative,
540 negative,
541 0,
542 unresolved,
543 unresolved};
544}
Kokkos::IndexType< std::size_t > Index

◆ reducePeriodicGaussianGLE() [2/2]

ReducedGaussianGLEResult gpr::quantum::reducePeriodicGaussianGLE ( const std::vector< Eigen::MatrixXd > & activeHessians,
const Eigen::MatrixXd & coupling,
const Eigen::MatrixXd & bathCurvature,
double step,
double unresolvedTolerance = 1e-12 )
inline

Definition at line 299 of file ReducedGaussianGLE.h.

303{
304 using Matrix = Eigen::MatrixXd;
305 const Eigen::Index beads = static_cast<Eigen::Index>(activeHessians.size());
306 const Eigen::Index active = coupling.rows(), bath = coupling.cols();
307 auto symmetric = [](const Matrix& matrix) {
308 return (matrix - matrix.transpose()).norm() <=
309 1e-12 * std::max(1., matrix.norm());
310 };
311 if (beads < 3 || active <= 0 || bath <= 0 || bathCurvature.rows() != bath ||
312 bathCurvature.cols() != bath || !coupling.allFinite() ||
313 !bathCurvature.allFinite() || !symmetric(bathCurvature) ||
314 !(step > 0.) || !std::isfinite(step) || !(unresolvedTolerance >= 0.) ||
315 !std::isfinite(unresolvedTolerance))
316 throw std::invalid_argument(
317 "Finite periodic action, coupling and symmetric bath required");
318 for (const auto& hessian: activeHessians)
319 if (hessian.rows() != active || hessian.cols() != active ||
320 !hessian.allFinite() || !symmetric(hessian))
321 throw std::invalid_argument(
322 "Matching finite symmetric active Hessians required");
323
324 Eigen::SelfAdjointEigenSolver<Matrix> bathEigen(bathCurvature);
325 if (bathEigen.info() != Eigen::Success ||
326 bathEigen.eigenvalues().minCoeff() <= 0.)
327 throw std::invalid_argument("The eliminated GLE bath must be positive");
328 const auto& frequencies = bathEigen.eigenvalues();
329 const Matrix modalCoupling = coupling * bathEigen.eigenvectors();
330 std::vector<Matrix> memory;
331 memory.reserve(static_cast<std::size_t>(beads));
332 for (Eigen::Index mode = 0; mode < beads; ++mode) {
333 const double sine = std::sin(std::acos(-1.) * mode / beads);
334 const double lambda = 4. * sine * sine / (step * step);
335 Eigen::VectorXd weights(bath);
336 for (Eigen::Index k = 0; k < bath; ++k)
337 weights[k] = lambda / (frequencies[k] * (frequencies[k] + lambda));
338 memory.push_back(modalCoupling * weights.asDiagonal() *
339 modalCoupling.transpose());
340 }
341
342 const Eigen::Index dimension = beads * active;
343 Matrix effective = Matrix::Zero(dimension, dimension);
344 for (Eigen::Index i = 0; i < beads; ++i) {
345 for (Eigen::Index j = 0; j < beads; ++j) {
346 const Eigen::Index separation = (j - i + beads) % beads;
347 Matrix kernel = Matrix::Zero(active, active);
348 for (Eigen::Index mode = 0; mode < beads; ++mode)
349 kernel.noalias() +=
350 std::cos(2. * std::acos(-1.) * mode * separation / beads) *
351 memory[mode];
352 kernel /= static_cast<double>(beads);
353 effective.block(i * active, j * active, active, active) =
354 step * kernel;
355 if (i == j)
356 effective.block(i * active, j * active, active, active) +=
357 step * activeHessians[i];
358 if (i == j)
359 effective.block(i * active, j * active, active, active)
360 .diagonal()
361 .array() += 2. / step;
362 if (j == (i + 1) % beads || i == (j + 1) % beads)
363 effective.block(i * active, j * active, active, active)
364 .diagonal()
365 .array() -= 1. / step;
366 }
367 }
368
369 const auto inertiaAndLogAbs = [unresolvedTolerance](const Matrix& matrix) {
370 Eigen::SelfAdjointEigenSolver<Matrix> eigen(matrix,
371 Eigen::EigenvaluesOnly);
372 if (eigen.info() != Eigen::Success || !eigen.eigenvalues().allFinite())
373 throw std::runtime_error("Periodic Gaussian GLE eigensolve failed");
374 Eigen::Index negative = 0, unresolved = 0;
375 double logAbs = 0.;
376 const double scale =
377 std::max(1., eigen.eigenvalues().cwiseAbs().maxCoeff());
378 for (double value: eigen.eigenvalues()) {
379 if (std::abs(value) <= unresolvedTolerance * scale) {
380 ++unresolved;
381 } else {
382 negative += value < 0.;
383 logAbs += std::log(std::abs(value));
384 }
385 }
386 return std::tuple<double, Eigen::Index, Eigen::Index>{logAbs, negative,
387 unresolved};
388 };
389
390 double bathLogAbs = 0.;
391 Eigen::Index bathNegative = 0, bathUnresolved = 0;
392 for (Eigen::Index mode = 0; mode < beads; ++mode) {
393 const double sine = std::sin(std::acos(-1.) * mode / beads);
394 const double lambda = 4. * sine * sine / (step * step);
395 for (Eigen::Index k = 0; k < bath; ++k) {
396 const double value = step * (frequencies[k] + lambda);
397 if (std::abs(value) <= unresolvedTolerance)
398 ++bathUnresolved;
399 else {
400 bathNegative += value < 0.;
401 bathLogAbs += std::log(std::abs(value));
402 }
403 }
404 }
405 const auto [effectiveLogAbs, effectiveNegative, effectiveUnresolved] =
406 inertiaAndLogAbs(effective);
407 const Eigen::Index fullNegative = bathNegative + effectiveNegative;
408 const Eigen::Index fullUnresolved = bathUnresolved + effectiveUnresolved;
409 return {std::move(effective), bathLogAbs,
410 effectiveLogAbs, bathLogAbs + effectiveLogAbs,
411 bathNegative, effectiveNegative,
412 fullNegative, bathUnresolved,
413 effectiveUnresolved, fullUnresolved};
414}

◆ referenceForceGradient()

ReferenceForceGradientValue gpr::quantum::referenceForceGradient ( const Eigen::VectorXd & residualGradient,
const std::function< Eigen::VectorXd(const Eigen::VectorXd &)> & residualHessianAction,
double step )
inline

Definition at line 23 of file ReferenceForceGradient.h.

28{
29 if (residualGradient.size() == 0 || !residualGradient.allFinite() ||
30 !residualHessianAction || !(step > 0) || !std::isfinite(step))
31 throw std::invalid_argument(
32 "Finite mass gradient, physical Hessian action and positive step "
33 "required");
34 const Eigen::VectorXd response = residualHessianAction(residualGradient);
35 if (response.size() != residualGradient.size() || !response.allFinite())
36 throw std::invalid_argument(
37 "Matching finite residual Hessian response required");
39 step * step * residualGradient.squaredNorm() / 24.,
40 step * step * response / 12.};
41 if (!std::isfinite(result.potentialCorrection) ||
42 !result.gradientCorrection.allFinite())
43 throw std::overflow_error(
44 "Nonfinite reference force-gradient correction");
45 return result;
46}

◆ referenceForceGradientQuadratic()

gpr::quantum::gaussian::Segment gpr::quantum::referenceForceGradientQuadratic ( const Eigen::MatrixXd & nativeCurvature,
const Eigen::MatrixXd & referenceCurvature,
double step,
bool corrected = true )
inline

Definition at line 50 of file ReferenceForceGradient.h.

54{
55 const auto d = nativeCurvature.rows();
56 if (d == 0 || nativeCurvature.cols() != d ||
57 referenceCurvature.rows() != d || referenceCurvature.cols() != d ||
58 !nativeCurvature.allFinite() || !referenceCurvature.allFinite() ||
59 (nativeCurvature - nativeCurvature.transpose()).norm() >
60 1e-12 * std::max(1., nativeCurvature.norm()) ||
61 (referenceCurvature - referenceCurvature.transpose()).norm() >
62 1e-12 * std::max(1., referenceCurvature.norm()))
63 throw std::invalid_argument(
64 "Matching finite symmetric native and reference curvature "
65 "required");
66 auto link = gpr::quantum::gaussian::exactSegment(referenceCurvature, step);
67 const Eigen::MatrixXd residual = nativeCurvature - referenceCurvature;
68 Eigen::MatrixXd endpoint = .5 * step * residual;
69 if (corrected)
70 endpoint.noalias() += step * step * step / 24. * residual * residual;
71 link.A += endpoint;
72 link.rightA = link.A;
73 if (!link.A.allFinite())
74 throw std::overflow_error("Nonfinite corrected Gaussian endpoint");
75 return link;
76}
Segment exactSegment(const Matrix &hessian, double duration)

◆ refineIsoenergyTurningPoints()

template<class NativeEvaluate, class NativeEnergy>
IsoenergyTurningPointRefinement gpr::quantum::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 )
inline

Definition at line 50 of file ConstrainedImaginaryTimePath.h.

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}

◆ refineNativeNewtonStep()

NativeNewtonKrylovResult gpr::quantum::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 )
inline

Definition at line 23 of file NativeNewtonKrylov.h.

29{
30 using V = Eigen::VectorXd;
31 using M = Eigen::MatrixXd;
32 const auto d = rhs.size();
33 if (!jacobian || !preconditioner || d < 1 || initial.size() != d ||
34 !rhs.allFinite() || !initial.allFinite() ||
35 !(relativeTolerance > 0 && relativeTolerance < 1) || !maximumIterations)
36 throw std::invalid_argument(
37 "Finite matching native Krylov controls required");
39 out.step = initial;
40 auto apply = [&](const V& v) {
41 V result = jacobian(v);
42 ++out.operatorCalls;
43 if (result.size() != d || !result.allFinite())
44 throw std::runtime_error("Invalid native Jacobian action");
45 return result;
46 };
47 if (rhs.norm() == 0) {
48 out.step = V::Zero(d);
49 out.converged = true;
50 return out;
51 }
52 const double target = relativeTolerance * rhs.norm();
53 const V residual = rhs - apply(initial);
54 const double beta = residual.norm();
55 out.residualNorm = beta;
56 if (beta <= target) {
57 out.converged = true;
58 return out;
59 }
60 const auto count = std::min<std::size_t>(maximumIterations, d);
61 M basis = M::Zero(d, count + 1), directions = M::Zero(d, count),
62 h = M::Zero(count + 1, count);
63 basis.col(0) = residual / beta;
64 for (std::size_t j = 0; j < count; ++j) {
65 V z = preconditioner(basis.col(j));
66 if (z.size() != d || !z.allFinite())
67 throw std::runtime_error("Invalid native Krylov preconditioner");
68 directions.col(j) = z;
69 V w = apply(z);
70 const double original = w.norm();
71 for (int pass = 0; pass < 2; ++pass)
72 for (std::size_t i = 0; i <= j; ++i) {
73 const double projection = basis.col(i).dot(w);
74 h(i, j) += projection;
75 w -= projection * basis.col(i);
76 }
77 h(j + 1, j) = w.norm();
78 const bool breakdown =
79 h(j + 1, j) <=
80 64 * std::numeric_limits<double>::epsilon() * original;
81 if (!breakdown) basis.col(j + 1) = w / h(j + 1, j);
82 V wanted = V::Zero(j + 2);
83 wanted[0] = beta;
84 const M small = h.topLeftCorner(j + 2, j + 1);
85 const V weights = small.colPivHouseholderQr().solve(wanted);
86 const double estimate = (small * weights - wanted).norm();
87 out.iterations = j + 1;
88 if (estimate <= target || breakdown || j + 1 == count) {
89 const V candidate = initial + directions.leftCols(j + 1) * weights;
90 const double actual = (rhs - apply(candidate)).norm();
91 if (actual < out.residualNorm) {
92 out.step = candidate;
93 out.residualNorm = actual;
94 }
95 if (actual <= target) {
96 out.converged = true;
97 return out;
98 }
99 if (breakdown) break;
100 }
101 }
102 return out;
103}
@ z
Definition Enums.h:28

◆ reflectOutgoingBand()

double gpr::quantum::reflectOutgoingBand ( std::vector< Eigen::VectorXd > & path)
inline

Definition at line 69 of file ReflectionEvenBand.h.

70{
71 if (path.size() < 3 || path.size() % 2 == 0)
72 throw std::invalid_argument(
73 "An odd closed band is required for outgoing reflection");
74 double correction = 0;
75 for (std::size_t j = 0; j < path.size() / 2; ++j) {
76 if (path[j].size() == 0 ||
77 path[j].size() != path[path.size() - 1 - j].size() ||
78 !path[j].allFinite() || !path[path.size() - 1 - j].allFinite())
79 throw std::invalid_argument(
80 "Matching finite outgoing and return coordinates required");
81 correction =
82 std::max(correction, (path[path.size() - 1 - j] - path[j]).norm());
83 path[path.size() - 1 - j] = path[j];
84 }
85 return correction;
86}

◆ regridGeodesicPath()

std::vector< Eigen::VectorXd > gpr::quantum::regridGeodesicPath ( const std::vector< Eigen::VectorXd > & path,
const std::vector< double > & weights = {} )
inline

Definition at line 17 of file ZeroEnergyGeodesic.h.

19 {})
20{
21 if (path.size() < 2 || path.front().size() < 1)
22 throw std::invalid_argument(
23 "A nonempty geodesic chart with two endpoints is required");
24 const auto count = weights.empty() ? path.size() : weights.size() + 1;
25 std::vector<double> arc(path.size(), 0), fraction(count, 0);
26 for (std::size_t j = 0; j < path.size(); ++j) {
27 if (path[j].size() != path.front().size() || !path[j].allFinite())
28 throw std::invalid_argument(
29 "Finite matching geodesic chart coordinates required");
30 if (j) {
31 const double length = (path[j] - path[j - 1]).norm();
32 if (!(length > 0) || !std::isfinite(length))
33 throw std::invalid_argument(
34 "Distinct finite geodesic chart nodes required");
35 arc[j] = arc[j - 1] + length;
36 }
37 }
38 if (!std::isfinite(arc.back()))
39 throw std::invalid_argument("Finite geodesic arclength required");
40 double scale = 1.;
41 if (!weights.empty())
42 scale = *std::max_element(weights.begin(), weights.end());
43 for (std::size_t j = 1; j < count; ++j) {
44 const double weight = weights.empty() ? 1. : weights[j - 1];
45 if (!(weight > 0) || !std::isfinite(weight))
46 throw std::invalid_argument(
47 "Positive finite geodesic sampling weights required");
48 fraction[j] = fraction[j - 1] + weight / scale;
49 if (!(fraction[j] > fraction[j - 1]) || !std::isfinite(fraction[j]))
50 throw std::invalid_argument(
51 "Resolved positive geodesic sampling fractions required");
52 }
53 std::vector<Eigen::VectorXd> result(count);
54 result.front() = path.front();
55 result.back() = path.back();
56 for (std::size_t j = 1; j + 1 < count; ++j) {
57 const double target = arc.back() * (fraction[j] / fraction.back());
58 const auto upper = std::upper_bound(arc.begin(), arc.end(), target);
59 const auto right = std::min(
60 path.size() - 1, static_cast<std::size_t>(upper - arc.begin()));
61 const auto left = right - 1;
62 const double t = (target - arc[left]) / (arc[right] - arc[left]);
63 result[j] = (1 - t) * path[left] + t * path[right];
64 }
65 return result;
66}

◆ reparameterizeLineIntegralString()

std::vector< Eigen::VectorXd > gpr::quantum::reparameterizeLineIntegralString ( const std::vector< Eigen::VectorXd > & path)
inline

Definition at line 18 of file LineIntegralString.h.

20{
21 if (path.size() < 3 || path.front().size() < 1)
22 throw std::invalid_argument(
23 "A line-integral string requires at least three nodes");
24 std::vector<double> arc(path.size(), 0.);
25 for (std::size_t j = 0; j < path.size(); ++j) {
26 if (path[j].size() != path.front().size() || !path[j].allFinite())
27 throw std::invalid_argument(
28 "Finite matching line-integral string coordinates required");
29 if (j) {
30 const double length = (path[j] - path[j - 1]).norm();
31 if (!(length > 0.) || !std::isfinite(length))
32 throw std::invalid_argument(
33 "Distinct adjacent line-integral string nodes required");
34 arc[j] = arc[j - 1] + length;
35 if (!std::isfinite(arc[j]))
36 throw std::overflow_error(
37 "Line-integral string length overflowed");
38 }
39 }
40 const double total = arc.back();
41 if (!(total > 0.) || !std::isfinite(total))
42 throw std::invalid_argument(
43 "A finite nonzero string length is required");
44 std::vector<Eigen::VectorXd> result(path.size());
45 result.front() = path.front();
46 result.back() = path.back();
47 std::size_t segment = 0;
48 for (std::size_t j = 1; j + 1 < path.size(); ++j) {
49 const double target = total * double(j) / double(path.size() - 1);
50 while (segment + 1 < arc.size() - 1 && arc[segment + 1] < target)
51 ++segment;
52 const double fraction =
53 (target - arc[segment]) / (arc[segment + 1] - arc[segment]);
54 result[j] =
55 path[segment] + fraction * (path[segment + 1] - path[segment]);
56 }
57 return result;
58}

◆ restoreLineIntegralInterior()

LineIntegralFeasibilityResult gpr::quantum::restoreLineIntegralInterior ( std::vector< Eigen::VectorXd > & trial,
std::vector< PotentialEvaluation > & values,
const std::vector< PotentialEvaluation > & source,
const LineIntegralNEBOptions & options,
const LineIntegralNEBBatch & native,
std::size_t maximumCorrections = 4 )
inline

Definition at line 387 of file LineIntegralNEB.h.

393{
394 if (trial.size() < 3 || values.size() != trial.size() ||
395 source.size() != trial.size() || !native ||
396 !(options.maximumStep > 0) || !std::isfinite(options.maximumStep) ||
397 !(options.energyTolerance > 0) ||
398 !std::isfinite(options.energyTolerance) ||
399 !std::isfinite(options.energy))
400 throw std::invalid_argument(
401 "Matching native LI-NEB trial, source and finite restoration "
402 "controls required");
404 for (std::size_t iteration = 0; iteration <= maximumCorrections;
405 ++iteration) {
406 std::vector<Eigen::VectorXd> probes;
407 std::vector<std::size_t> indices;
408 for (std::size_t j = 1; j + 1 < trial.size(); ++j) {
409 if (!(source[j].energy > options.energy) ||
410 !std::isfinite(source[j].energy) ||
411 !std::isfinite(values[j].energy) ||
412 values[j].gradient.size() != trial[j].size() ||
413 !values[j].gradient.allFinite() || !trial[j].allFinite())
414 throw std::invalid_argument(
415 "Finite native interiors and a feasible source required");
416 if (values[j].energy > options.energy) continue;
417 if (iteration == maximumCorrections) return result;
418 const double norm2 = values[j].gradient.squaredNorm();
419 if (!(norm2 > 0) || !std::isfinite(norm2)) return result;
420 const double margin =
421 std::max(4 * options.energyTolerance,
422 .1 * (source[j].energy - options.energy));
423 Eigen::VectorXd step =
424 ((options.energy + margin - values[j].energy) / norm2) *
425 values[j].gradient;
426 const double length = step.norm();
427 if (!std::isfinite(length)) return result;
428 if (length > options.maximumStep)
429 step *= options.maximumStep / length;
430 probes.push_back(trial[j] + step);
431 indices.push_back(j);
432 }
433 if (indices.empty()) {
434 result.feasible = true;
435 return result;
436 }
437 const auto returned = native(probes);
438 ++result.batchEvaluations;
439 result.pointEvaluations += probes.size();
440 if (returned.size() != probes.size())
441 throw std::runtime_error(
442 "Native interior correction batch shape differs");
443 for (std::size_t k = 0; k < indices.size(); ++k)
444 if (!std::isfinite(returned[k].energy) ||
445 returned[k].gradient.size() != probes[k].size() ||
446 !returned[k].gradient.allFinite())
447 throw std::runtime_error(
448 "Native interior correction has no finite matching return");
449 for (std::size_t k = 0; k < indices.size(); ++k) {
450 trial[indices[k]] = probes[k];
451 values[indices[k]] = returned[k];
452 }
453 }
454 return result;
455}

◆ restrictGeodesicProposal()

ZeroEnergyGeodesicPotential gpr::quantum::restrictGeodesicProposal ( ZeroEnergyGeodesicPotential model,
std::vector< Eigen::VectorXd > center,
double radius )
inline

Definition at line 16 of file GeodesicProposalTrust.h.

19{
20 if (center.empty() || !(radius > 0) || !std::isfinite(radius) ||
21 !model.evaluate || !model.searchHessians)
22 throw std::invalid_argument(
23 "A finite positive geodesic proposal domain and model are "
24 "required");
25 const auto d = center.front().size();
26 for (const auto& q: center)
27 if (d <= 0 || q.size() != d || !q.allFinite())
28 throw std::invalid_argument(
29 "Consistent finite geodesic domain centers required");
30 auto check = [center = std::move(center),
31 radius](const std::vector<Eigen::VectorXd>& q) {
32 if (q.size() != center.size())
33 throw std::invalid_argument(
34 "Geodesic proposal domain image count differs");
35 for (std::size_t j = 0; j < q.size(); ++j) {
36 if (q[j].size() != center[j].size() || !q[j].allFinite())
37 throw std::invalid_argument(
38 "Geodesic proposal domain coordinates differ");
39 if ((q[j] - center[j]).norm() > radius * (1 + 1e-12))
40 throw std::domain_error(
41 "Geodesic model trial exceeds the native displacement "
42 "domain");
43 }
44 };
45 auto evaluate = model.evaluate;
46 auto hessians = model.searchHessians;
47 model.evaluate = [check, evaluate](const auto& q) {
48 check(q);
49 return evaluate(q);
50 };
51 model.searchHessians = [check, hessians](const auto& q) {
52 check(q);
53 return hessians(q);
54 };
55 return model;
56}
void check(int status)
Definition gpridge.hpp:323

◆ retractGeodesicMesh()

std::vector< Eigen::VectorXd > gpr::quantum::retractGeodesicMesh ( const std::vector< Eigen::VectorXd > & path,
const std::vector< double > & weights,
double tolerance,
const Eigen::VectorXd & target = {} )
inline

Retract a path onto prescribed link-length constraints by moving only interior nodes along their mesh tangents. Endpoint geometries are fixed. A target (1-s)*g(q) preserves the first-order Newton step from an infeasible path; target zero gives the constrained mesh manifold. This operation evaluates no potential and carries no cached values.

Definition at line 93 of file GeodesicMeshProjection.h.

96 {})
97{
98 using namespace meshprojection_detail;
99 if (!(tolerance > 0.) || !std::isfinite(tolerance))
100 throw std::invalid_argument(
101 "Positive mesh projection tolerance required");
102 auto current = path;
103 auto data = geometry(current, weights);
104 const auto m = data.constraint.size();
105 Vector goal = Vector::Zero(m);
106 if (target.size()) goal = target;
107 if (goal.size() != m || !goal.allFinite())
108 throw std::invalid_argument(
109 "Finite matching mesh constraint target required");
110 for (unsigned iteration = 0; iteration < 32; ++iteration) {
111 const Vector residual = data.constraint - goal;
112 const double error = residual.cwiseAbs().maxCoeff();
113 if (error <= tolerance) return current;
114 Matrix jacobian = Matrix::Zero(m, m);
115 for (Eigen::Index row = 0; row < m; ++row) {
116 const auto j = static_cast<std::size_t>(row + 1);
117 const double hm = data.leftWeight[j], hp = data.rightWeight[j],
118 sum = hm + hp;
119 jacobian(row, row) =
120 2 *
121 (hp * data.leftUnit[j] + hm * data.rightUnit[j])
122 .dot(data.tangent[j]) /
123 sum;
124 if (row)
125 jacobian(row, row - 1) =
126 -2 * hp * data.leftUnit[j].dot(data.tangent[j - 1]) / sum;
127 if (row + 1 < m)
128 jacobian(row, row + 1) =
129 -2 * hm * data.rightUnit[j].dot(data.tangent[j + 1]) / sum;
130 }
131 Eigen::FullPivLU<Matrix> factor(jacobian);
132 if (factor.rank() != m)
133 throw std::domain_error(
134 "Geodesic tangential mesh Jacobian is singular");
135 const Vector step = factor.solve(-residual);
136 if (!step.allFinite() ||
137 (jacobian * step + residual).stableNorm() >
138 1e-10 * std::max(1., residual.stableNorm()))
139 throw std::domain_error("Unresolved geodesic mesh correction");
140 bool accepted = false;
141 double scale = 1.;
142 for (unsigned trial = 0; trial < 24; ++trial, scale *= .5) {
143 auto candidate = current;
144 for (Eigen::Index row = 0; row < m; ++row)
145 candidate[row + 1] += scale * step[row] * data.tangent[row + 1];
146 try {
147 auto next = geometry(candidate, weights);
148 if ((next.constraint - goal).cwiseAbs().maxCoeff() < error) {
149 current = std::move(candidate);
150 data = std::move(next);
151 accepted = true;
152 break;
153 }
154 } catch (const std::domain_error&) {
155 }
156 }
157 if (!accepted)
158 throw std::domain_error(
159 "Geodesic mesh correction does not decrease the constraint");
160 }
161 throw std::domain_error("Geodesic mesh projection iteration limit");
162}

◆ sameGPBandPoint()

bool gpr::quantum::sameGPBandPoint ( const Eigen::VectorXd & left,
const Eigen::VectorXd & right )
inline

Definition at line 15 of file GPBandNodeAcquisition.h.

17{
18 return left.size() > 0 && left.size() == right.size() &&
19 (left - right).cwiseAbs().maxCoeff() <=
20 128 * std::numeric_limits<double>::epsilon() *
21 std::max({1., left.cwiseAbs().maxCoeff(),
22 right.cwiseAbs().maxCoeff()});
23}

◆ sampleBondCenteredImaginaryTimeRing()

std::vector< Eigen::VectorXd > gpr::quantum::sampleBondCenteredImaginaryTimeRing ( const ConstrainedImaginaryTimeTrajectory & trajectory,
std::size_t fullBeads )
inline

Definition at line 327 of file ConstrainedImaginaryTimePath.h.

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}
std::vector< ConstrainedImaginaryTimeSample > samples

◆ selectGPBandNodes()

std::vector< GPBandNodeScore > gpr::quantum::selectGPBandNodes ( const std::vector< Eigen::VectorXd > & points,
const std::vector< double > & massGradientVariance,
const Eigen::VectorXd & weights,
const std::vector< Eigen::VectorXd > & measured,
std::size_t maximumNodes )
inline

Definition at line 33 of file GPBandNodeAcquisition.h.

38{
39 if (points.empty() || points.size() != massGradientVariance.size() ||
40 weights.size() != static_cast<Eigen::Index>(points.size()) ||
41 !weights.allFinite() || (weights.array() < 0).any())
42 throw std::invalid_argument(
43 "Matching finite band acquisition inputs required");
44 const auto d = points.front().size();
45 if (!d)
46 throw std::invalid_argument(
47 "Nonempty band acquisition coordinates required");
48 for (const auto& point: measured)
49 if (point.size() != d || !point.allFinite())
50 throw std::invalid_argument(
51 "Matching finite measured coordinates required");
52 std::vector<GPBandNodeScore> scores;
53 for (std::size_t j = 0; j < points.size(); ++j) {
54 if (points[j].size() != d || !points[j].allFinite() ||
55 !(massGradientVariance[j] >= 0) ||
56 !std::isfinite(massGradientVariance[j]))
57 throw std::invalid_argument(
58 "Finite nonnegative band force variance required");
59 if (std::any_of(measured.begin(), measured.end(),
60 [&](const auto& point) {
61 return sameGPBandPoint(point, points[j]);
62 }))
63 continue;
64 const double contribution =
65 weights[j] * weights[j] * massGradientVariance[j];
66 if (!std::isfinite(contribution))
67 throw std::overflow_error(
68 "Band acquisition score exceeds arithmetic range");
69 const auto found =
70 std::find_if(scores.begin(), scores.end(), [&](const auto& score) {
71 return sameGPBandPoint(points[score.node], points[j]);
72 });
73 if (found == scores.end())
74 scores.push_back({j, contribution});
75 else {
76 found->forceVariance += contribution;
77 if (!std::isfinite(found->forceVariance))
78 throw std::overflow_error(
79 "Grouped band acquisition score exceeds arithmetic range");
80 }
81 }
82 std::stable_sort(scores.begin(), scores.end(),
83 [](const auto& left, const auto& right) {
84 return left.forceVariance > right.forceVariance;
85 });
86 scores.erase(std::remove_if(scores.begin(), scores.end(),
87 [](const auto& score) {
88 return score.forceVariance == 0;
89 }),
90 scores.end());
91 if (scores.size() > maximumNodes) scores.resize(maximumNodes);
92 return scores;
93}

◆ solveArcTailNewton() [1/2]

ArcTailNewtonStep gpr::quantum::solveArcTailNewton ( const ArcTailEvaluation & evaluation,
const std::vector< Eigen::MatrixXd > & orthonormalNormals,
const Eigen::VectorXd & constraintCorrection )

◆ solveArcTailNewton() [2/2]

ArcTailNewtonStep gpr::quantum::solveArcTailNewton ( const ArcTailEvaluation & state,
const std::vector< M > & normals,
const V & correction )

Definition at line 28 of file ArcTailNewton.cpp.

31{
32 const auto n = state.gradient.size();
33 if (n < 2 || state.fluctuationSegments.size() != n ||
34 state.durationCrossGradient.size() != n || normals.size() != n ||
35 correction.size() < 1 || !correction.allFinite() ||
36 !std::isfinite(state.durationGradient) ||
37 !std::isfinite(state.durationHessian))
38 throw std::invalid_argument(
39 "Matching finite arc-tail derivatives, links and constraint blocks "
40 "required");
41 const auto d = state.gradient.front().size(), k = correction.size();
42 M normal(n * d, k);
43 V gradient(n * d), cross(n * d);
44 for (std::size_t j = 0; j < n; ++j) {
45 if (state.gradient[j].size() != d ||
46 state.durationCrossGradient[j].size() != d ||
47 normals[j].rows() != d || normals[j].cols() != k ||
48 !state.gradient[j].allFinite() ||
49 !state.durationCrossGradient[j].allFinite() ||
50 !normals[j].allFinite())
51 throw std::invalid_argument(
52 "Arc-tail Newton metric or derivative dimensions differ");
53 normal.middleRows(j * d, d) = normals[j];
54 gradient.segment(j * d, d) = state.gradient[j];
55 cross.segment(j * d, d) = state.durationCrossGradient[j];
56 }
57 if ((normal.transpose() * normal - M::Identity(k, k)).norm() > 1e-10)
58 throw std::invalid_argument(
59 "Arc-tail constraint normals must be jointly orthonormal");
60 const V particular = normal * correction;
61 M sources(n * d, 2);
62 sources.col(0) =
63 -gradient - applyKernel(state.fluctuationSegments, particular);
64 sources.col(1) = cross;
65 const auto solved = gaussian::solveRestrictedTraceKernel(
66 state.fluctuationSegments, M::Identity(d, d), normal, sources);
67 const V first = solved.values.col(0), response = solved.values.col(1);
68 const double contraction = cross.dot(response);
69 const double schur = state.durationHessian - contraction;
70 const double tolerance =
71 128 * std::numeric_limits<double>::epsilon() *
72 (std::abs(state.durationHessian) + std::abs(contraction));
73 if (!std::isfinite(schur) || std::abs(schur) <= tolerance)
74 throw std::runtime_error(
75 "Arc-tail duration equation has an unresolved Schur complement");
76 ArcTailNewtonStep result;
77 result.durationSchurComplement = schur;
78 result.durationDisplacement =
79 (-state.durationGradient - cross.dot(particular) - cross.dot(first)) /
80 schur;
81 const V step = particular + first - response * result.durationDisplacement;
82 result.multipliers =
83 solved.multipliers.col(0) -
84 solved.multipliers.col(1) * result.durationDisplacement;
85 const V spatial = applyKernel(state.fluctuationSegments, step) +
86 cross * result.durationDisplacement +
87 normal * result.multipliers + gradient;
88 const double temporal =
89 cross.dot(step) + state.durationHessian * result.durationDisplacement +
90 state.durationGradient;
91 result.relativeEquationResidual =
92 std::hypot(spatial.norm(), temporal) /
93 std::max(1., std::hypot(gradient.norm(), state.durationGradient));
94 result.constraintResidual = (normal.transpose() * step - correction).norm();
95 if (!step.allFinite() || !std::isfinite(result.durationDisplacement) ||
96 result.relativeEquationResidual > 1e-8 ||
97 result.constraintResidual > 1e-10)
98 throw std::runtime_error(
99 "Arc-tail Newton step fails its joint coordinate and energy "
100 "equations");
101 for (std::size_t j = 0; j < n; ++j)
102 result.displacement.push_back(step.segment(j * d, d));
103 return result;
104}
RestrictedKernelSolution solveRestrictedTraceKernel(const std::vector< Segment > &segments, const Matrix &twist, const Matrix &orthonormalNormals, const Matrix &sources)
std::vector< Eigen::VectorXd > durationCrossGradient

◆ solveFixedTimeArcNewton()

ArcTailNewtonStep gpr::quantum::solveFixedTimeArcNewton ( const ArcTailEvaluation & state,
const std::vector< Eigen::MatrixXd > & normals,
const Eigen::VectorXd & correction )
inline

Definition at line 18 of file FixedTimeArc.h.

21{
22 using M = Eigen::MatrixXd;
23 using V = Eigen::VectorXd;
24 const auto n = state.gradient.size();
25 if (n < 2 || state.fluctuationSegments.size() != n || normals.size() != n ||
26 correction.size() < 1 || !correction.allFinite())
27 throw std::invalid_argument(
28 "Matching fixed-time arc gradients, links and constraints "
29 "required");
30 const auto d = state.gradient.front().size(), k = correction.size();
31 M normal(n * d, k);
32 V gradient(n * d);
33 for (std::size_t j = 0; j < n; ++j) {
34 if (state.gradient[j].size() != d || !state.gradient[j].allFinite() ||
35 normals[j].rows() != d || normals[j].cols() != k ||
36 !normals[j].allFinite())
37 throw std::invalid_argument(
38 "Fixed-time arc metric or constraints differ");
39 normal.middleRows(j * d, d) = normals[j];
40 gradient.segment(j * d, d) = state.gradient[j];
41 }
42 if ((normal.transpose() * normal - M::Identity(k, k)).norm() > 1e-10)
43 throw std::invalid_argument(
44 "Fixed-time arc constraints must be jointly orthonormal");
45 auto apply = [&](const V& q) {
46 V out = V::Zero(n * d);
47 for (std::size_t j = 0; j < n; ++j) {
48 const auto next = (j + 1) % n;
49 const auto& link = state.fluctuationSegments[j];
50 out.segment(j * d, d) +=
51 link.A * q.segment(j * d, d) - link.L * q.segment(next * d, d);
52 out.segment(next * d, d) +=
53 link.rightEndpoint() * q.segment(next * d, d) -
54 link.L.transpose() * q.segment(j * d, d);
55 }
56 return out;
57 };
58 const V particular = normal * correction;
59 const M sources = -gradient - apply(particular);
60 const auto solved = gaussian::solveRestrictedTraceKernel(
61 state.fluctuationSegments, M::Identity(d, d), normal, sources);
62 const V step = particular + solved.values.col(0);
63 ArcTailNewtonStep result;
64 result.multipliers = solved.multipliers.col(0);
65 result.relativeEquationResidual =
66 (apply(step) + normal * result.multipliers + gradient).norm() /
67 std::max(1., gradient.norm());
68 result.constraintResidual = (normal.transpose() * step - correction).norm();
69 if (!step.allFinite() || result.relativeEquationResidual > 1e-8 ||
70 result.constraintResidual > 1e-10)
71 throw std::runtime_error(
72 "Fixed-time arc Newton equations are unresolved");
73 for (std::size_t j = 0; j < n; ++j)
74 result.displacement.push_back(step.segment(j * d, d));
75 return result;
76}

◆ solveTwistedConstraints() [1/2]

TwistedConstraintStep gpr::quantum::solveTwistedConstraints ( const std::vector< Eigen::MatrixXd > & diagonal,
const std::vector< Eigen::VectorXd > & gradient,
const std::vector< Eigen::MatrixXd > & normals,
const Eigen::MatrixXd & coupling,
const Eigen::MatrixXd & twist,
const Eigen::VectorXd & correction )

Definition at line 26 of file TwistedConstraintNewton.cpp.

32{
33 using Matrix = Eigen::MatrixXd;
34 using Vector = Eigen::VectorXd;
35 if (diagonal.empty() || gradient.size() != diagonal.size() ||
36 normals.size() != diagonal.size() || !coupling.allFinite() ||
37 !correction.allFinite())
38 throw std::invalid_argument("Invalid twisted constrained chain");
39 const std::size_t n = diagonal.size();
40 const Eigen::Index d = gradient.front().size(), k = correction.size();
41 if (coupling.rows() != d || coupling.cols() != d ||
42 (coupling - coupling.transpose()).norm() >
43 64 * std::numeric_limits<double>::epsilon() * d *
44 std::max(1., coupling.norm()))
45 throw std::invalid_argument(
46 "Finite symmetric matrix coupling required");
47 if (!d || twist.rows() != d || twist.cols() != d || !twist.allFinite() ||
48 (twist.transpose() * twist - Matrix::Identity(d, d)).norm() > 1e-12 * d)
49 throw std::invalid_argument("Expected orthogonal twist");
50 Matrix gram = Matrix::Zero(k, k);
51 for (std::size_t j = 0; j < n; ++j) {
52 if (diagonal[j].rows() != d || diagonal[j].cols() != d ||
53 gradient[j].size() != d || normals[j].rows() != d ||
54 normals[j].cols() != k || !diagonal[j].allFinite() ||
55 !gradient[j].allFinite() || !normals[j].allFinite() ||
56 (diagonal[j] - diagonal[j].transpose()).norm() >
57 64 * std::numeric_limits<double>::epsilon() * d *
58 diagonal[j].norm())
59 throw std::invalid_argument("Inconsistent constrained blocks");
60 gram += normals[j].transpose() * normals[j];
61 }
62 if ((gram - Matrix::Identity(k, k)).norm() > 1e-10 * k)
63 throw std::invalid_argument(
64 "Constraint columns must be globally orthonormal");
65 TwistedConstraintStep result;
66 Matrix reduced = Matrix::Zero(d + k, d + k);
67 Vector right(d + k);
68 std::vector<Matrix> solved, inverse;
69 if (n == 1) {
70 reduced.topLeftCorner(d, d) =
71 diagonal[0] - coupling * twist - twist.transpose() * coupling;
72 reduced.topRightCorner(d, k) = normals[0];
73 reduced.bottomLeftCorner(k, d) = normals[0].transpose();
74 right.head(d) = -gradient[0];
75 right.tail(k) = correction;
76 } else {
77 std::vector<Matrix> forward;
78 for (std::size_t j = 1; j < n; ++j) {
79 Matrix pivot = diagonal[j], rhs = Matrix::Zero(d, d + 1 + k);
80 if (j == 1) rhs.leftCols(d) -= coupling;
81 if (j + 1 == n) rhs.leftCols(d) -= coupling * twist;
82 rhs.col(d) = gradient[j];
83 rhs.rightCols(k) = normals[j];
84 if (j > 1) {
85 pivot -= coupling * inverse.back() * coupling;
86 rhs += coupling * forward.back();
87 }
88 Eigen::FullPivLU<Matrix> factor(pivot);
89 if (!factor.isInvertible()) return result;
90 inverse.push_back(factor.solve(Matrix::Identity(d, d)));
91 forward.push_back(factor.solve(rhs));
92 if (!inverse.back().allFinite() || !forward.back().allFinite())
93 return result;
94 }
95 solved = forward;
96 for (std::size_t j = n - 2; j > 0; --j)
97 solved[j - 1] += inverse[j - 1] * coupling * solved[j];
98 const Matrix btSolve = -coupling * solved.front() -
99 twist.transpose() * coupling * solved.back();
100 reduced.topLeftCorner(d, d) = diagonal[0] - btSolve.leftCols(d);
101 reduced.topRightCorner(d, k) = normals[0] - btSolve.rightCols(k);
102 reduced.bottomLeftCorner(k, d) =
103 reduced.topRightCorner(d, k).transpose();
104 Matrix qSolveQ = Matrix::Zero(k, k);
105 Vector qSolveG = Vector::Zero(k);
106 for (std::size_t j = 1; j < n; ++j) {
107 qSolveQ += normals[j].transpose() * solved[j - 1].rightCols(k);
108 qSolveG += normals[j].transpose() * solved[j - 1].col(d);
109 }
110 reduced.bottomRightCorner(k, k) = -qSolveQ;
111 right.head(d) = -gradient[0] + btSolve.col(d);
112 right.tail(k) = correction + qSolveG;
113 }
114 if (!reduced.allFinite() || !right.allFinite()) return result;
115 Eigen::FullPivLU<Matrix> border(reduced);
116 if (!border.isInvertible()) return result;
117 const Vector endpoint = border.solve(right);
118 if (!endpoint.allFinite()) return result;
119 result.multipliers = endpoint.tail(k);
120 result.displacement.push_back(endpoint.head(d));
121 for (std::size_t j = 1; j < n; ++j)
122 result.displacement.push_back(
123 -solved[j - 1].col(d) -
124 solved[j - 1].leftCols(d) * endpoint.head(d) -
125 solved[j - 1].rightCols(k) * result.multipliers);
126 double error = 0, scale = 0;
127 Vector projected = Vector::Zero(k);
128 for (std::size_t j = 0; j < n; ++j) {
129 Vector residual = diagonal[j] * result.displacement[j] +
130 normals[j] * result.multipliers + gradient[j];
131 if (j) residual -= coupling * result.displacement[j - 1];
132 if (j + 1 < n) residual -= coupling * result.displacement[j + 1];
133 if (!j)
134 residual -=
135 twist.transpose() * coupling * result.displacement.back();
136 if (j + 1 == n)
137 residual -= coupling * twist * result.displacement.front();
138 error = std::max(error, residual.norm());
139 scale = std::max(scale, gradient[j].norm());
140 projected += normals[j].transpose() * result.displacement[j];
141 if (!result.displacement[j].allFinite()) return result;
142 }
143 result.relativeResidual = error / std::max(1.0, scale);
144 result.constraintResidual = (projected - correction).norm();
145 result.invertible = std::isfinite(result.relativeResidual) &&
146 std::isfinite(result.constraintResidual);
147 return result;
148}

◆ solveTwistedConstraints() [2/2]

TwistedConstraintStep gpr::quantum::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 )

Definition at line 11 of file TwistedConstraintNewton.cpp.

16{
17 if (!(coupling > 0) || !std::isfinite(coupling) || diagonal.empty())
18 throw std::invalid_argument("Finite positive scalar coupling required");
19 const Eigen::MatrixXd matrix =
20 coupling * Eigen::MatrixXd::Identity(diagonal.front().rows(),
21 diagonal.front().rows());
22 return solveTwistedConstraints(diagonal, gradient, normals, matrix, twist,
23 correction);
24}

◆ solveZeroEnergyGeodesicStep()

std::vector< Eigen::VectorXd > gpr::quantum::solveZeroEnergyGeodesicStep ( const ZeroEnergyGeodesicEvaluation & state)

Definition at line 249 of file ZeroEnergyGeodesic.cpp.

251{
252 const auto n = state.residual.size();
253 require(n >= 3 && state.lower.size() == n && state.diagonal.size() == n &&
254 state.upper.size() == n,
255 "Geodesic Jacobian blocks required");
256 const auto d = state.residual.front().size();
257 require(d > 0, "Nonempty geodesic metric required");
258 for (std::size_t j = 0; j < n; ++j) {
259 require(state.residual[j].size() == d && state.residual[j].allFinite(),
260 "Invalid geodesic Newton source");
261 for (const M* block:
262 {&state.lower[j], &state.diagonal[j], &state.upper[j]})
263 require(
264 block->rows() == d && block->cols() == d && block->allFinite(),
265 "Invalid geodesic Newton block");
266 }
267 std::vector<M> forward(n);
268 std::vector<V> rhs(n), step(n);
269 for (std::size_t j = 0; j < n; ++j) {
270 M pivot = state.diagonal[j];
271 V source = -state.residual[j];
272 if (j) {
273 pivot -= state.lower[j] * forward[j - 1];
274 source -= state.lower[j] * rhs[j - 1];
275 }
276 Eigen::FullPivLU<M> solve(pivot);
277 if (solve.rank() != d)
278 throw std::runtime_error("Unresolved geodesic block pivot");
279 rhs[j] = solve.solve(source);
280 if (j + 1 < n) forward[j] = solve.solve(state.upper[j]);
281 }
282 for (std::size_t j = n; j-- > 0;)
283 step[j] = j + 1 == n ? rhs[j] : V(rhs[j] - forward[j] * step[j + 1]);
284 double error = 0, scale = 0;
285 for (std::size_t j = 0; j < n; ++j) {
286 V r = state.diagonal[j] * step[j] + state.residual[j];
287 if (j) r += state.lower[j] * step[j - 1];
288 if (j + 1 < n) r += state.upper[j] * step[j + 1];
289 error += r.squaredNorm();
290 scale += state.residual[j].squaredNorm();
291 }
292 if (!std::isfinite(error) ||
293 std::sqrt(error) > 1e-8 * std::max(1., std::sqrt(scale)))
294 throw std::runtime_error(
295 "Geodesic step fails its original block equations");
296 return step;
297}
std::vector< Eigen::MatrixXd > diagonal
std::vector< Eigen::VectorXd > residual

◆ stationaryBathReference()

Eigen::MatrixXd gpr::quantum::stationaryBathReference ( const Eigen::MatrixXd & saddleCurvature,
const Eigen::MatrixXd & reactionDirections )

Complete a saddle curvature into a stable bath that annihilates reactionDirections. Columns use mass coordinates and must span a negative-definite restriction. The complementary Schur curvature must be positive semidefinite. Neither a fitted physical bath nor a stationary-point index is inferred from this reference.

Definition at line 27 of file HarmonicReference.cpp.

29{
30 const auto d = hessian.rows(), k = directions.cols();
31 if (!d || !k || k > d || directions.rows() != d || !directions.allFinite())
32 throw std::invalid_argument(
33 "Finite nonempty matching reaction directions required");
34 symmetric(hessian, d);
35 Eigen::ColPivHouseholderQR<Eigen::MatrixXd> qr(directions);
36 if (qr.rank() != k)
37 throw std::invalid_argument("Independent reaction directions required");
38 const Eigen::MatrixXd q =
39 qr.householderQ() * Eigen::MatrixXd::Identity(d, d);
40 const Eigen::MatrixXd v = q.leftCols(k), w = q.rightCols(d - k);
41 const Eigen::MatrixXd a = v.transpose() * hessian * v;
42 const double tolerance =
43 128 * std::numeric_limits<double>::epsilon() * d * hessian.norm();
44 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> gram(a);
45 if (gram.info() != Eigen::Success || !gram.eigenvalues().allFinite() ||
46 gram.eigenvalues().maxCoeff() >= -tolerance)
47 throw std::invalid_argument(
48 "Reaction restriction must be resolved negative definite");
49 if (k == d) return Eigen::MatrixXd::Zero(d, d);
50 const Eigen::MatrixXd b = v.transpose() * hessian * w;
51 const Eigen::MatrixXd schur =
52 w.transpose() * hessian * w - b.transpose() * a.ldlt().solve(b);
53 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> bath(
54 .5 * (schur + schur.transpose()));
55 if (bath.info() != Eigen::Success || !bath.eigenvalues().allFinite() ||
56 bath.eigenvalues().minCoeff() < -tolerance)
57 throw std::invalid_argument(
58 "Reaction span leaves an unstable bath direction");
59 const Eigen::MatrixXd factor =
60 w * bath.eigenvectors() *
61 bath.eigenvalues().cwiseMax(0.).cwiseSqrt().asDiagonal();
62 const Eigen::MatrixXd result = factor * factor.transpose();
63 if (!result.allFinite())
64 throw std::overflow_error("Nonfinite stationary bath reference");
65 return result;
66}

◆ surrogatePathResidualMerit()

double gpr::quantum::surrogatePathResidualMerit ( const PotentialPathResult & result)
inline

Definition at line 16 of file SurrogatePathTrust.h.

17{
18 const auto& gradient = result.fullGradient;
19 if (gradient.empty() || gradient.size() % 2 || gradient.front().size() == 0)
20 throw std::invalid_argument(
21 "Nonempty even reflected residuals required");
22 const auto dimension = gradient.front().size();
23 double merit = 0;
24 for (const auto& value: gradient) {
25 if (value.size() != dimension || !value.allFinite())
26 throw std::invalid_argument(
27 "Finite matching reflected residual dimensions required");
28 merit += .5 * value.squaredNorm();
29 }
30 if (!std::isfinite(merit))
31 throw std::invalid_argument("Finite reflected residual merit required");
32 return merit;
33}

◆ validateReflectionEvenBand()

template<class Constraints>
void gpr::quantum::validateReflectionEvenBand ( const std::vector< Eigen::VectorXd > & path,
const std::vector< double > & weights,
const Constraints & constraints,
double tolerance )

Definition at line 16 of file ReflectionEvenBand.h.

20{
21 const auto n = path.size();
22 if (n < 3 || n % 2 == 0 || weights.size() + 1 != n || !(tolerance > 0) ||
23 !std::isfinite(tolerance))
24 throw std::invalid_argument(
25 "An odd reflected band, matching links and positive tolerance "
26 "required");
27 const auto d = path.front().size();
28 if (d == 0)
29 throw std::invalid_argument("Nonempty reflection coordinates required");
30 const double roundoff = 128 * std::numeric_limits<double>::epsilon();
31 for (std::size_t j = 0; j < n; ++j) {
32 const auto& q = path[j];
33 const auto& reflected = path[n - 1 - j];
34 if (q.size() != d || reflected.size() != d || !q.allFinite() ||
35 !reflected.allFinite() ||
36 (q - reflected).norm() >
37 roundoff * std::max({1., q.norm(), reflected.norm()}))
38 throw std::invalid_argument(
39 "Native reflection search requires an explicitly reflected CON "
40 "seed");
41 }
42 for (std::size_t j = 0; j < weights.size(); ++j)
43 if (!(weights[j] > 0) || !std::isfinite(weights[j]) ||
44 std::abs(weights[j] - weights[weights.size() - 1 - j]) >
45 roundoff * std::max(1., std::abs(weights[j])))
46 throw std::invalid_argument(
47 "Reflection search requires palindromic positive "
48 "imaginary-time links");
49 const auto k = constraints.target.size();
50 if (!constraints.target.allFinite() ||
51 constraints.target.norm() > tolerance ||
52 (k > 0 && constraints.normals.size() != n))
53 throw std::invalid_argument(
54 "Reflection search requires compatible odd phase constraints");
55 if (k > 0)
56 for (std::size_t j = 0; j < n; ++j) {
57 const auto& a = constraints.normals[j];
58 const auto& b = constraints.normals[n - 1 - j];
59 if (a.rows() != d || a.cols() != k || b.rows() != d ||
60 b.cols() != k || !a.allFinite() || !b.allFinite() ||
61 (a + b).norm() > roundoff * std::max({1., a.norm(), b.norm()}))
62 throw std::invalid_argument(
63 "Reflection search requires odd phase normals");
64 }
65}

◆ weightedEventBound()

long double gpr::quantum::weightedEventBound ( const GaussianPolynomialMoments & moments,
long double probabilityBound )

Definition at line 133 of file GaussianPolynomial.cpp.

135{
136 if (!std::isfinite(probabilityBound) || probabilityBound < 0 ||
137 probabilityBound > 1)
138 throw std::invalid_argument(
139 "Expected an event probability bound between zero and one");
140 if (!std::isfinite(moments.second.value) ||
141 !std::isfinite(moments.second.absoluteRoundoffBound) ||
142 moments.second.absoluteRoundoffBound < 0)
143 throw std::invalid_argument(
144 "Invalid Gaussian second moment or error allowance");
145 const Real upper =
146 addUp(moments.second.value, moments.second.absoluteRoundoffBound);
147 if (upper < 0)
148 throw std::runtime_error("Negative Gaussian polynomial second moment");
149 if (probabilityBound == 0) return 0;
150 return upward(std::sqrt(multiplyUp(upper, probabilityBound)));
151}