27#pragma clang fp contract(off)
28#elif defined(__GNUC__)
29#pragma GCC optimize("fp-contract=off")
38constexpr double kLbfgsEps = 1e-30;
41void mulAddInto(Eigen::VectorXd &y,
double a,
const Eigen::VectorXd &x) {
42 const Eigen::Index n = y.size();
43 double *yd = y.data();
44 const double *xd = x.data();
45 for (Eigen::Index i = 0; i < n; ++i) {
46 yd[i] = yd[i] + a * xd[i];
50[[nodiscard]] Eigen::VectorXd mulAdd(
const Eigen::VectorXd &y,
double a,
51 const Eigen::VectorXd &x) {
52 Eigen::VectorXd out = y;
53 mulAddInto(out, a, x);
57void maybeProjectRigid(Eigen::VectorXd &vec,
const Eigen::VectorXd &pos,
59 if (!enabled || pos.size() < 6 || pos.size() % 3 != 0) {
62 const long nat = pos.size() / 3;
63 const AtomMatrix coords = Eigen::Map<const AtomMatrix>(pos.data(), nat, 3);
67std::vector<int> twoLoopIndex(
int nPairs,
int extra) {
69 idx.reserve(
static_cast<size_t>(nPairs + std::max(extra, 0)));
70 for (
int i = 0; i < nPairs; ++i) {
73 for (
int k = 0; k < extra && nPairs > 0; ++k) {
74 idx.push_back(nPairs - 1);
82Eigen::Vector3d
LBFGS::micRij(
const Eigen::VectorXd &pos,
int i,
int j)
const {
83 Eigen::Vector3d dr = pos.segment<3>(3 * i) - pos.segment<3>(3 * j);
89 const std::string &p =
m_optConfig.opts.lbfgs.precon;
90 return p ==
"exp" || p ==
"c1" || p ==
"lindh" || p ==
"lindh_full" ||
91 p ==
"pair" || p ==
"pair_abs" || p ==
"pair_full" || p ==
"fischer" ||
92 p ==
"schlegel" || p ==
"swart";
98 cfg.precon_mu, cfg.precon_rcut, *
m_objf);
102 const Eigen::VectorXd &pos)
const {
104 if (
usesPrecon() && pos.size() >= 6 && pos.size() % 3 == 0) {
108 Eigen::PartialPivLU<Eigen::MatrixXd> lu(P);
109 const Eigen::VectorXd z = lu.solve(q);
113 QUILL_LOG_DEBUG(
m_log,
"[LBFGS] Packwood P failed to factor, using H0 I");
119 const Eigen::VectorXd &a_f) {
120 Eigen::VectorXd r =
m_objf->getPositions();
121 Eigen::VectorXd f = a_f;
124 m_optConfig.opts.lbfgs.inverse_curvature * f, a_maxMove);
126 maybeProjectRigid(f, r,
m_optConfig.opts.lbfgs.project_rigid);
127 const Eigen::VectorXd g = -f;
133 const int n =
static_cast<int>(H.rows());
134 Eigen::MatrixXd A = Eigen::MatrixXd::Zero(n + 1, n + 1);
135 A.topLeftCorner(n, n) = H;
136 A.col(n).head(n) = g;
137 A.row(n).head(n) = g.transpose();
138 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(A);
139 if (es.info() != Eigen::Success) {
142 const Eigen::VectorXd v = es.eigenvectors().col(0);
143 if (std::abs(v(n)) < 1.0e-14) {
146 d = v.head(n) / v(n);
149 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(H);
150 if (es.info() != Eigen::Success) {
153 Eigen::VectorXd ev = es.eigenvalues();
154 const double lmin = ev.minCoeff();
155 const double mu = (lmin < 1.0e-8) ? (1.0e-8 - lmin) : 0.0;
157 d = -es.eigenvectors() *
158 (es.eigenvectors().transpose() * g).cwiseQuotient(ev);
160 maybeProjectRigid(d, r,
m_optConfig.opts.lbfgs.project_rigid);
166 if (
step ==
"newton" ||
step ==
"rfo") {
169 double H0 =
m_optConfig.opts.lbfgs.inverse_curvature;
170 Eigen::VectorXd r =
m_objf->getPositions();
171 Eigen::VectorXd f = a_f;
172 maybeProjectRigid(f, r,
m_optConfig.opts.lbfgs.project_rigid);
176 const Eigen::VectorXd y =
m_fPrev - f;
183 m_log,
"[LBFGS] Negative curvature: {:.4f} eV/A^2 take max move step",
191 if (
m_optConfig.opts.lbfgs.auto_scale && sy > 0.0 && yy > 0.0) {
192 const double g_syyy = sy / yy;
193 const double g_sssy = ss / sy;
197 }
else if (h0 ==
"adaptive") {
198 H0 = std::min(g_syyy, g_sssy);
202 if (
m_optConfig.opts.lbfgs.max_inverse_curvature > 0.0) {
203 H0 = std::min(H0,
m_optConfig.opts.lbfgs.max_inverse_curvature);
205 QUILL_LOG_DEBUG(
m_log,
"[LBFGS] H0={:.4e} ({} scale)", H0, h0);
209 const std::optional<double> known =
211 ?
m_objf->knownCurvature()
220 constexpr double kSteepMode = 30.0;
221 bool knownFits =
false;
222 if (known && std::isfinite(*known) && *known > 0.0) {
223 double hKnown = 1.0 / *known;
224 if (
m_optConfig.opts.lbfgs.max_inverse_curvature > 0.0) {
225 hKnown = std::min(hKnown,
m_optConfig.opts.lbfgs.max_inverse_curvature);
228 if (knownMotion < a_maxMove || *known < kSteepMode) {
231 QUILL_LOG_DEBUG(
m_log,
"[LBFGS] H0={:.4e} (known curvature)", H0);
235 m_objf->supportsFiniteDifferenceCurvature()) {
238 Eigen::VectorXd dg =
m_objf->getGradient(
true) + a_f;
243 QUILL_LOG_WARNING(
m_log,
244 "[LBFGS] Negative curvature calculated via FD: {:.4e} "
245 "eV/A^2, take max move step",
250 QUILL_LOG_DEBUG(
m_log,
"[LBFGS] Curvature calculated via FD: {:.4e} eV/A^2",
255 twoLoopIndex(
static_cast<int>(
m_s.size()),
256 static_cast<int>(
m_optConfig.opts.lbfgs.extra_updates));
257 const int loopmax =
static_cast<int>(idx.size());
258 std::vector<double> a(
static_cast<size_t>(loopmax));
260 Eigen::VectorXd q = -f;
262 for (
int k = loopmax - 1; k >= 0; k--) {
263 const int i = idx[
static_cast<size_t>(k)];
264 a[
static_cast<size_t>(k)] =
265 m_rho[
static_cast<size_t>(i)] *
267 mulAddInto(q, -a[
static_cast<size_t>(k)],
m_y[
static_cast<size_t>(i)]);
270 Eigen::VectorXd z =
applyH0(q, H0, r);
272 for (
int k = 0; k < loopmax; k++) {
273 const int i = idx[
static_cast<size_t>(k)];
274 const double b =
m_rho[
static_cast<size_t>(i)] *
276 mulAddInto(z, a[
static_cast<size_t>(k)] - b,
m_s[
static_cast<size_t>(i)]);
279 Eigen::VectorXd d = -z;
282 if (distance >= a_maxMove &&
m_optConfig.opts.lbfgs.distance_reset) {
283 QUILL_LOG_DEBUG(
m_log,
284 "[LBFGS] reset memory, proposed step too large: {:.4f}",
297 if (angle > 90.0 &&
m_optConfig.opts.lbfgs.angle_reset) {
298 QUILL_LOG_DEBUG(
m_log,
299 "[LBFGS] reset memory, angle between LBFGS angle and "
300 "force too large: {:.4f}",
306 maybeProjectRigid(d, r,
m_optConfig.opts.lbfgs.project_rigid);
318 const Eigen::VectorXd &a_f1,
const Eigen::VectorXd &a_f0,
319 double a_e1,
double a_e0) {
320 Eigen::VectorXd s0 =
m_objf->difference(a_r1, a_r0);
323 Eigen::VectorXd y0 = a_f0 - a_f1;
326 const std::string &curv = cfg.curvature;
327 const double H0 = std::max(cfg.inverse_curvature, 1.0e-16);
330 if (cfg.secant ==
"zhangxu" &&
m_objf->gradientMatchesEnergy() &&
337 const double theta = t - sy;
338 mulAddInto(y0, theta / ss, s0);
340 QUILL_LOG_DEBUG(
m_log,
"[LBFGS] Zhang-Xu θ={:.4e} s·ŷ={:.4e}", theta, sy);
343 double sBs = ss / H0;
344 if (
usesPrecon() && a_r1.size() >= 6 && a_r1.size() % 3 == 0) {
350 const double sn = std::sqrt(ss);
353 if (curv ==
"cautious") {
355 const double thresh =
356 cfg.cautious_eps * ss *
357 std::pow(std::max(gnorm, 1.0e-30), cfg.cautious_alpha);
359 QUILL_LOG_DEBUG(
m_log,
"[LBFGS] Li-Fukushima skip, s·y={:.4e} < {:.4e}",
363 }
else if (std::abs(sy) < kLbfgsEps || (curv !=
"reset" && sy < 0.2 * sBs)) {
364 if (curv ==
"skip") {
365 QUILL_LOG_DEBUG(
m_log,
"[LBFGS] skip pair, s·y={:.4e}", sy);
368 if (curv ==
"damped" && sBs > sy) {
369 const double theta = std::clamp(0.8 * sBs / (sBs - sy), 0.0, 1.0);
370 const Eigen::VectorXd B0s =
371 (
usesPrecon() && a_r1.size() >= 6 && a_r1.size() % 3 == 0)
373 : Eigen::VectorXd(s0 / H0);
374 y0 = theta * y0 + (1.0 - theta) * B0s;
376 QUILL_LOG_DEBUG(
m_log,
"[LBFGS] Powell damp θ={:.3f} s·ŷ={:.4e}", theta,
378 }
else if (std::abs(sy) < kLbfgsEps) {
379 QUILL_LOG_WARNING(
m_log,
380 "[LBFGS] s0.y0 too small ({:.4e}), resetting memory",
387 if (!std::isfinite(sy)) {
388 QUILL_LOG_WARNING(
m_log,
"[LBFGS] non-finite s·y, resetting memory");
394 if (curv !=
"reset" && sy <= 1.0e-8 * sn * yn) {
395 QUILL_LOG_DEBUG(
m_log,
"[LBFGS] overlap skip, s·y={:.4e}", sy);
400 m_s.push_back(std::move(s0));
401 m_y.push_back(std::move(y0));
413 Eigen::VectorXd r =
m_objf->getPositions();
414 Eigen::VectorXd f = -
m_objf->getGradient();
415 const std::string &accept =
m_optConfig.opts.lbfgs.accept;
416 const bool energyTests =
m_objf->gradientMatchesEnergy();
417 const bool energyRequested = accept ==
"energy" || accept ==
"nonmonotone" ||
419 if (energyRequested && !energyTests &&
m_iteration == 0) {
421 "lbfgs_secant = {}): a band or saddle objective's "
422 "gradient is not its energy gradient",
425 const bool energyAccept =
426 energyTests && (accept ==
"energy" || accept ==
"nonmonotone");
429 (energyTests &&
m_optConfig.opts.lbfgs.secant ==
"zhangxu");
430 const double e0 = needE ?
m_objf->getEnergy() : 0.0;
438 Eigen::VectorXd dr =
getStep(a_maxMove, f);
440 constexpr double max_erise = 1.0e-8;
442 if (accept ==
"nonmonotone" && !
m_eHist.empty()) {
446 bool accepted =
false;
448 for (
int dec = 0; dec < 10; ++dec) {
449 m_objf->setPositions(mulAdd(r, alpha, dr));
450 e_acc =
m_objf->getEnergy();
451 if (e_acc - ref <= max_erise) {
462 e_acc =
m_objf->getEnergy();
469 m_objf->setPositions(r + dr);
478 return m_objf->isConverged() ? 1 : 0;
484 status =
step(a_maxMove);
488 return m_objf->isConverged() ? 1 : 0;
Eigen::Matrix< double, Eigen::Dynamic, 3, eOnStorageOrder > AtomMatrix
#define EONC_LOG_WARNING(...)
std::deque< double > m_rho
int update(const Eigen::VectorXd &a_r1, const Eigen::VectorXd &a_r0, const Eigen::VectorXd &a_f1, const Eigen::VectorXd &a_f0, double a_e1, double a_e0)
std::deque< Eigen::VectorXd > m_y
std::deque< double > m_eHist
std::deque< Eigen::VectorXd > m_s
int step(double a_maxMove) override
int run(size_t a_maxIterations, double a_maxMove) override
Eigen::VectorXd hessianStep(double a_maxMove, const Eigen::VectorXd &a_f)
eonc::log::FileScoped m_log
Eigen::MatrixXd buildPrecon(const Eigen::VectorXd &pos) const
Eigen::VectorXd applyH0(const Eigen::VectorXd &q, double H0, const Eigen::VectorXd &pos) const
Eigen::VectorXd getStep(double a_maxMove, const Eigen::VectorXd &a_f)
Eigen::Vector3d micRij(const Eigen::VectorXd &pos, int i, int j) const
const OptimizerConfig m_optConfig
std::shared_ptr< ObjectiveFunction > m_objf
double squaredNorm(const Eigen::MatrixBase< A > &x)
A::PlainObject normalized(const Eigen::MatrixBase< A > &x, double min_norm=1e-300)
x / norm(x), or zero below min_norm (the safemath convention).
double norm(const Eigen::MatrixBase< A > &x)
sqrt of the correctly rounded squared norm; IEEE sqrt is itself correctly rounded,...
double dot(const double *x, const double *y, std::size_t n)
Round-to-nearest-even value of the exact sum of x[i] * y[i].
double orderedDot(const double *x, const double *y, std::size_t n)
A fixed summation tree: four lanes (term i goes to lane i mod 4, each lane a left-to-right sum of rou...
void projectOutRotTrans(Eigen::VectorXd &step, const AtomMatrix &positions)
VectorXd maxAtomMotionAppliedV(const VectorXd v1, double maxMotion)
double maxAtomMotionV(const VectorXd v1)
Eigen::MatrixXd build(const Eigen::VectorXd &pos, const std::string &kind, PotType pot, double A, double mu, double rcut_in, ObjectiveFunction &objf)
Analytic pair or model Hessian.
constexpr double safe_div(double num, double denom, double fallback=0.0)
double safe_acos(double x)
constexpr double safe_recip(double x, double fallback=0.0)
RAII resource manager for the ARTn C library with global synchronization.