Loading...
Searching...
No Matches
MinModeSaddleSearch.cpp
Go to the documentation of this file.
1/*
2** This file is part of eOn.
3**
4** SPDX-License-Identifier: BSD-3-Clause
5**
6** Copyright (c) 2010--present, eOn Development Team
7** All rights reserved.
8**
9** Repo:
10** https://github.com/TheochemUI/eOn
11*/
15#include "eon/EonLogger.h"
16#include "eon/EpiCenters.h"
18#include "eon/HelperFunctions.h"
20#include "eon/PrfoRefine.h"
21#include "eon/SaddleSearchJob.h"
22#include "eon/SafeMath.h"
23#include "eon/eonExceptions.hpp"
24
25#include <algorithm>
26#include <cmath>
27#include <format>
28#include <fstream>
29#include <memory>
30#include <stdexcept>
31#include <string>
32
33namespace eonc {
34
35namespace {
36
37// Twenty halvings leave 2^-20 of the attempted step, about 10^-6.
38// For the default max_move of 0.2 Å that remainder is 2e-7 Å, which
39// is still above the motion floor, so this ceiling is what stops a
40// long step. The floor stops a shorter one first.
41constexpr int kMaxEnergyHalvings = 20;
42
43// Each stall reseeds and halves the cap, and the seed sign alternates.
44// Six stalls is three tries of each sign, and the cap has dropped by
45// 64. Both seeds have been repeated at three step sizes.
46constexpr int kMaxEnergyStalls = 6;
47
48// A kept fraction below 1/64 has been halved more than six times.
49// The mode was estimated for the full step. A piece that small is a
50// different displacement, so the rotational CG or L-BFGS state is
51// dropped and the next estimate starts from the original tangent.
52constexpr double kMaxEnergyReseedAlpha = 1.0 / 64.0;
53
54// Smallest translation cap, in Å. The default finite-difference
55// distance is 1e-2 Å and the saddle ini files use 1e-3 Å. A cap
56// below 1e-4 Å is smaller than those probes. Holding it here keeps
57// the next attempt a real move, and it stays above the motion floor.
58constexpr double kMaxEnergyStepFloor = 1.0e-4;
59
60// Max-atom motion, in Å, below which a probe repeats a geometry
61// already evaluated. L-BFGS uses the same 1e-8 scale to drop a
62// secant pair whose overlap is numerical noise.
63constexpr double kMaxEnergyMotionFloor = 1.0e-8;
64
65// One doubling per accepted under-limit step, the inverse of the
66// probe halving. Each legal step gives back one factor the wall
67// removed. The default max_move of 0.2 Å returns from the step
68// floor in ceil(log2(0.2/1e-4)) = 11 legal steps.
69constexpr double kMaxEnergyCapRegrowth = 2.0;
70
71// Crossings of max_energy in one search, whether a probe was found
72// or the centre was restored. Six consecutive stalls already stop a
73// search that never finds a legal point. A found probe, or one
74// under-limit step, resets that counter and the cap doubles back,
75// so a search sitting on the limit crosses once a regrowth cycle
76// until max_iterations. Sixteen is more than one full regrowth of
77// a 0.2 Å cap from the step floor (11) and more than the stall
78// budget. The LJ38 dimer start this recovery finishes crosses
79// once, so the cap does not cut that search off. Past sixteen the
80// search is pinned and ends with the high-energy status. The
81// default max_iterations is 1000, and each crossing can spend 20
82// probes.
83constexpr int kMaxEnergyWallEvents = 16;
84
85} // namespace
86
88private:
89 std::shared_ptr<Matter> matter;
91 std::shared_ptr<EigenmodeStrategy> minModeMethod;
92 int iteration{0};
93 double reactantEnergy{0.0};
94
95public:
97 std::shared_ptr<Matter> matterPassed,
98 std::shared_ptr<EigenmodeStrategy> minModeMethodPassed,
99 AtomMatrix modePassed, double reactantEnergyPassed,
100 const Parameters &paramsPassed)
101 : ObjectiveFunction(paramsPassed),
102 matter{std::move(matterPassed)},
103 eigenvector{std::move(modePassed)},
104 minModeMethod{minModeMethodPassed},
105 reactantEnergy{reactantEnergyPassed} {}
106
107 ~MinModeObjectiveFunction() override = default;
108
109 // |C_tau| is the curvature of the potential along the mode. The
110 // translated force is F - 2 (F·tau) tau, and that force has a
111 // different curvature. Improved dimer and Lanczos do not report the
112 // mode scale, so their first L-BFGS step measures F_eff. That probe
113 // is what the LJ13 and Pt heptamer force-call counts follow.
114 //
115 // The classic dimer (improved = false) is the adatom AKMC catalogue
116 // path. It reports the negative mode curvature. L-BFGS keeps the
117 // capped scale for a mild mode whose uncapped step exceeds max_move,
118 // and probes F_eff for a steep overrun.
119 //
120 // With rgsaddle the rotation of every dimer and Lanczos search is
121 // one solver type, so the C++ class does not say which search this
122 // is. The scale follows the dimer setting.
123 std::optional<double> knownCurvature() const override {
124 if (iteration == 0 || !minModeMethod) {
125 return std::nullopt;
126 }
127 if (params.saddle_search_options().minmode_method !=
129 params.dimer_options().improved) {
130 return std::nullopt;
131 }
133 if (!std::isfinite(c) || c >= 0.0) {
134 return std::nullopt;
135 }
136 return -c;
137 }
138
139 // The translation force has its component along the mode reversed, so
140 // the search climbs the potential energy that getEnergy() returns.
141 bool gradientMatchesEnergy() const override { return false; }
142
143 // A new centre and the mode solver's first displaced image along the
144 // current mode are independent evaluations; a batching potential takes
145 // them together, and compute() then finds the image evaluated.
146 // Finite-difference gradient probes never call compute(), so they
147 // evaluate the centre alone.
149 if (matter->needsForceUpdate()) {
150 minModeMethod->evaluateWithProbe(matter, eigenvector);
151 }
152 }
153
154 // The centre (and a batching solver's first image) is evaluated
155 // here. FIRE then skips getGradient() when this is true, so the
156 // mode is not rotated at a point the search will pull back.
157 bool pastClimbCeiling() override {
159 return getEnergy() - reactantEnergy >
160 params.saddle_search_options().max_energy;
161 }
162
163 VectorXd getGradient(bool fdstep = false) {
164 if (!fdstep || iteration == 0) {
166 }
167 AtomMatrix force = matter->getForces();
168
169 if (!fdstep || iteration == 0) {
171 // Check if ImprovedDimer lost the mode
172 auto *dimer = eonc::asImprovedDimer(*minModeMethod);
173 if (dimer && !dimer->rotationDidConverge) {
174 if (dimer->getEigenvalue() < 0.0) {
177 "[MinMode] Dimer restored to best state with C_tau={:.4f}",
178 dimer->getEigenvalue());
180 } else {
182 }
183 }
184 iteration++;
185 }
186
188 double eigenvalue = eonc::eigenmodeGetEigenvalue(*minModeMethod);
189 // OCI-NEB returns a positive-curvature image to the band before
190 // translating it away from the current path.
191 if (eigenvalue > 0.0 &&
192 params.neb_options().climbing_image.ocineb.use_mmf) {
194 }
195
196 AtomMatrix proj = matDot(force, eigenvector) *
197 eonc::safemath::safe_normalized(eigenvector);
198
199 if (eigenvalue > 0.0) {
200 if (params.saddle_search_options().perp_force_ratio > 0.0) {
201 double d = params.saddle_search_options().perp_force_ratio;
202 force = d * force - (1.0 + d) * proj;
203 } else if (params.saddle_search_options().confine_positive.enabled) {
204 if (params.saddle_search_options().confine_positive.bowl_breakout) {
205 AtomMatrix forceTemp = matter->getForces();
206 const long nAtoms = matter->numberOfAtoms();
207 int nBowlActive = static_cast<int>(std::min<long>(
208 params.saddle_search_options().confine_positive.bowl_active,
209 nAtoms));
210 if (nBowlActive <= 0) {
211 force.setZero();
212 } else {
213 std::vector<int> indices_max(nBowlActive);
214
215 // Find the nBowlActive atoms with largest forces
216 for (int j = 0; j < nBowlActive; j++) {
217 double f_max = forceTemp.row(0).norm();
218 int i_max = 0;
219 for (long i = 0; i < matter->numberOfAtoms(); i++) {
220 if (f_max < forceTemp.row(i).norm()) {
221 f_max = forceTemp.row(i).norm();
222 i_max = static_cast<int>(i);
223 }
224 }
225 forceTemp.row(i_max).setZero();
226 indices_max[j] = i_max;
227 }
228 forceTemp.setZero();
229 for (int j = 0; j < nBowlActive; j++) {
230 forceTemp.row(indices_max[j]) = -proj.row(indices_max[j]);
231 }
232 force = forceTemp;
233 }
234 } else {
235 int sufficientForce = 0;
236 double minForce =
237 params.saddle_search_options().confine_positive.min_force;
238 const long maxBoostTries = std::max(
239 3 * matter->numberOfAtoms(),
240 params.saddle_search_options().confine_positive.min_active);
241 long boostTries = 0;
242 while (
243 sufficientForce <
244 params.saddle_search_options().confine_positive.min_active &&
245 boostTries < maxBoostTries) {
246 sufficientForce = 0;
247 force = matter->getForces();
248 for (long i = 0; i < matter->numberOfAtoms(); i++) {
249 for (int k = 0; k < 3; k++) {
250 if (std::abs(force(i, k)) < minForce) {
251 force(i, k) = 0;
252 } else {
253 sufficientForce++;
254 force(i, k) =
255 -params.saddle_search_options().confine_positive.boost *
256 proj(i, k);
257 }
258 }
259 }
260 minForce *=
261 params.saddle_search_options().confine_positive.scale_ratio;
262 boostTries++;
263 }
264 }
265 } else {
266 force = -proj;
267 }
268 } else {
269 force += -2.0 * proj;
270 }
271
272 VectorXd forceV = VectorXd::Map(force.data(), 3 * matter->numberOfAtoms());
273 return -forceV;
274 }
275
276 // No prefetch here: an energy-accepting optimizer reads trial points
277 // that may be rejected.
278 double getEnergy() { return matter->getPotentialEnergy(); }
279 void setPositions(const VectorXd &x) { matter->setPositionsV(x); }
280 VectorXd getPositions() { return matter->getPositionsV(); }
281 int degreesOfFreedom() { return 3 * matter->numberOfAtoms(); }
282 bool isConverged() {
283 return getConvergence() < params.saddle_search_options().converged_force;
284 }
285
286 double getConvergence() {
288 if (params.optimizer_options().convergence_metric == "norm") {
289 return matter->getForcesFreeV().norm();
290 } else if (params.optimizer_options().convergence_metric == "max_atom") {
291 return matter->maxForce();
292 } else if (params.optimizer_options().convergence_metric ==
293 "max_component") {
294 return matter->getForces().cwiseAbs().maxCoeff();
295 } else {
296 EONC_LOG_CRITICAL("[MinModeSaddleSearch] unknown convergence metric: {}",
297 params.optimizer_options().convergence_metric);
298 throw std::invalid_argument(
299 std::format("[MinModeSaddleSearch] unknown convergence_metric: {}",
300 params.optimizer_options().convergence_metric));
301 }
302 }
303
304 VectorXd difference(const VectorXd &a, const VectorXd &b) {
305 return matter->pbcV(a - b);
306 }
307
308 // Drop the rotation memory and start the next estimate from seed.
309 // A translation that has walked into a wall keeps the old rotational
310 // CG or L-BFGS state, and that state repeats the same climb.
311 void reseedMode(const AtomMatrix &seed) {
312 eigenvector = seed;
313 if (auto *dimer = eonc::asImprovedDimer(*minModeMethod)) {
314 dimer->init_cg = true;
315 dimer->init_lbfgs = true;
316 dimer->s.clear();
317 dimer->y.clear();
318 dimer->rho.clear();
319 dimer->gradients.clear();
320 dimer->positions.clear();
321 }
322 }
323};
324
325MinModeSaddleSearch::MinModeSaddleSearch(std::shared_ptr<Matter> matterPassed,
326 AtomMatrix modePassed,
327 double reactantEnergyPassed,
328 const Parameters &parametersPassed,
329 std::shared_ptr<Potential> potPassed)
330 : SaddleSearchMethod(potPassed, parametersPassed),
331 matter{matterPassed} {
333 params.optimizer_options().convergence_metric, "[MinModeSaddleSearch]");
335 reactantEnergy = reactantEnergyPassed;
336 mode = modePassed;
337 initialTangent_ = modePassed;
339 iteration = 0;
340
342
343 // Set reference mode for ImprovedDimer (prevents mode switching)
344 if (auto *dimer = eonc::asImprovedDimer(*minModeMethod)) {
345 VectorXd refVec = VectorXd::Map(mode.data(), 3 * matter->numberOfAtoms());
346 refVec = refVec.array() * matter->getFreeV().array();
347 dimer->setReferenceMode(refVec);
348 }
349}
350
352 return run(params.saddle_search_options().max_iterations);
353}
354
355int MinModeSaddleSearch::runRetainFrames(long max_iterations_override) {
357 climb_frames_.clear();
358 const long maxIter = max_iterations_override < 0
359 ? params.saddle_search_options().max_iterations
360 : max_iterations_override;
361 const int st = run(maxIter);
362 retain_climb_frames_ = false;
363 return st;
364}
365
366int MinModeSaddleSearch::run(long max_iterations_override) {
367 long effectiveMaxIter = max_iterations_override;
368 QUILL_LOG_DEBUG(
369 log, "Saddle point search started from reactant with energy {} eV.",
371
372 int optStatus;
373 bool firstIteration = true;
374 const char *forceLabel =
375 params.optimizer_options().convergence_metric_label.c_str();
376
377 if (params.saddle_search_options().minmode_method ==
379 QUILL_LOG_DEBUG(
380 log, "================= Using the GP Dimer Library =================");
383 QUILL_LOG_DEBUG(log, "GPR eigenvalue: {}",
386 return status;
387 }
388 if (getEigenvalue() > 0.0 && status == STATUS_GOOD) {
389 QUILL_LOG_DEBUG(log, "[MinModeSaddleSearch] eigenvalue not negative");
391 }
393 params.saddle_search_options().zero_mode_abort_curvature) {
394 QUILL_LOG_DEBUG(log, "Zero mode eigenvalue: {}",
397 }
400 } else {
401
402 if (params.saddle_search_options().minmode_method ==
404 QUILL_LOG_INFO(log,
405 "[Dimer] {:9s} {:9s} {:10s} {:18s} {:9s} "
406 "{:7s} {:6s} {:4s} {:5s}\n",
407 "Step", "Step Size", "Delta E", forceLabel, "Curvature",
408 "Torque", "Angle", "Rots", "Align");
409 } else if (params.saddle_search_options().minmode_method ==
411 QUILL_LOG_INFO(
412 log,
413 "[Lanczos] {:9s} {:9s} {:10s} {:18s} {:9s} {:10s} {:7s} {:5s}\n",
414 "Step", "Step Size", "Delta E", forceLabel, "Curvature", "Rel Change",
415 "Angle", "Iters");
416 } else if (params.saddle_search_options().minmode_method ==
418 QUILL_LOG_INFO(log,
419 "[GPRDimer] {:9s} {:9s} {:10s} {:18s} {:9s} "
420 " {:7s} {:6s} {:4s}\n",
421 "Step", "Step Size", "Delta E", forceLabel, "Curvature",
422 "Torque", "Angle", "Rots");
423 }
424
425 std::string climbLabel = "climb";
426 std::string climbDatFilename = "climb.dat";
427
428 AtomMatrix initialPosition = matter->getPositions();
429
430 auto objf = std::make_shared<MinModeObjectiveFunction>(
432 auto write_climb_frame = [&](uint64_t frameIndex, bool append,
433 double stepSize, double de, double conv,
434 double eigenval, double torque, double angle,
435 long rotations) {
437 metadata.frame_index = frameIndex;
438 metadata.energy = matter->getPotentialEnergy();
439 metadata.scalars.push_back({"step_size", stepSize});
440 metadata.scalars.push_back({"delta_e", de});
441 metadata.scalars.push_back({"convergence", conv});
442 metadata.scalars.push_back({"eigenvalue", eigenval});
443 metadata.scalars.push_back({"torque", torque});
444 metadata.scalars.push_back({"angle", angle});
445 metadata.scalars.push_back({"rotations", static_cast<double>(rotations)});
447 climb_frames_.push_back(eonc::io::matterToConFrame(*matter, &metadata));
448 }
449 if (params.debug_options().write_movies) {
450 if (!eonc::io::io_ok(
451 matter->matter2con(climbLabel, append, &metadata))) {
452 QUILL_LOG_WARNING(log, "Failed to write climb movie frame {}",
453 climbLabel);
454 }
455 eonc::helpers::saveMode(std::format("mode_{:03}.dat", frameIndex),
456 matter,
458 }
459
460 if (params.debug_options().write_deprecated_outs) {
461 std::ofstream climbDat(climbDatFilename,
462 append ? (std::ios::binary | std::ios::app)
463 : std::ios::binary);
464 if (climbDat) {
465 if (!append) {
466 climbDat << "iteration\tstep_size\tdelta_e\tconvergence"
467 "\teigenvalue\ttorque\tangle\trotations\n";
468 }
469 climbDat << std::format("{}\t{:.7e}\t{:.6f}\t{:.5e}\t{:.6f}"
470 "\t{:.6f}\t{:.4f}\t{}\n",
471 frameIndex, stepSize, de, conv, eigenval,
472 torque, angle, rotations);
473 }
474 }
475 };
476 if (params.debug_options().write_movies || retain_climb_frames_) {
477 write_climb_frame(0, false, 0.0, 0.0, objf->getConvergence(),
479 0);
480 }
481 if (params.saddle_search_options().nonnegative_displacement_abort) {
482 objf->getGradient();
484 QUILL_LOG_DEBUG(log, "Nonnegative eigenvalue: {}",
487 return status;
488 }
489 }
490
492 objf, params.optimizer_options().method, params);
493
494 // Stock max_move stays the cap until a translation crosses max_energy.
495 // A search that never crosses it takes the same steps as before.
496 const double stockMove = params.optimizer_options().max_move;
497 double translationCap = stockMove;
498 int wallStalls = 0;
499 int wallEvents = 0;
500 int reseeds = 0;
501 int probeForceCalls = 0;
502 auto probedEnergy = [&]() {
503 const long beforeCalls = matter->getForceCalls();
504 const double energy = objf->getEnergy();
505 probeForceCalls +=
506 static_cast<int>(matter->getForceCalls() - beforeCalls);
507 return energy;
508 };
509 auto pullUnderEnergy = [&](const VectorXd &before) -> bool {
510 const double limit = params.saddle_search_options().max_energy;
511 const VectorXd after = objf->getPositions();
512 const VectorXd delta = objf->difference(after, before);
513 double alpha = 0.5;
514 bool found = false;
515 for (int probe = 0; probe < kMaxEnergyHalvings; ++probe) {
516 if (eonc::geometry::maxAtomMotionV(alpha * delta) <
517 kMaxEnergyMotionFloor) {
518 break;
519 }
520 objf->setPositions(before + alpha * delta);
521 if (probedEnergy() - reactantEnergy <= limit) {
522 found = true;
523 break;
524 }
525 alpha *= 0.5;
526 }
527 auto freshMode = [&]() {
529 if (reseeds % 2 == 1) {
530 seed = -seed;
531 }
532 objf->reseedMode(seed);
533 ++reseeds;
534 };
535 if (found) {
536 wallStalls = 0;
537 ++wallEvents;
538 const double accepted = eonc::geometry::maxAtomMotionV(alpha * delta);
539 translationCap =
540 std::min(stockMove, std::max(accepted, kMaxEnergyStepFloor));
541 if (alpha < kMaxEnergyReseedAlpha) {
542 freshMode();
543 QUILL_LOG_DEBUG(
544 log,
545 "[MinMode] energy above max_energy {:.4f}, shortened "
546 "the translation to {:.3e} and re-initialised the mode",
547 limit, accepted);
548 } else {
549 QUILL_LOG_DEBUG(log,
550 "[MinMode] energy above max_energy {:.4f}, shortened "
551 "the translation to {:.3e}",
552 limit, accepted);
553 }
554 if (wallEvents >= kMaxEnergyWallEvents) {
555 QUILL_LOG_DEBUG(log,
556 "[MinMode] {} crossings of max_energy {:.4f}, "
557 "ending the search",
558 wallEvents, limit);
559 return false;
560 }
561 return true;
562 }
563 objf->setPositions(before);
564 if (probedEnergy() - reactantEnergy > limit) {
565 return false;
566 }
567 ++wallEvents;
568 ++wallStalls;
569 translationCap = std::min(
570 stockMove, std::max(translationCap * 0.5, kMaxEnergyStepFloor));
571 freshMode();
572 QUILL_LOG_DEBUG(log,
573 "[MinMode] translation stays above max_energy {:.4f}, "
574 "restored the centre and re-initialised the mode",
575 limit);
576 if (wallEvents >= kMaxEnergyWallEvents) {
577 QUILL_LOG_DEBUG(log,
578 "[MinMode] {} crossings of max_energy {:.4f}, "
579 "ending the search",
580 wallEvents, limit);
581 return false;
582 }
583 return wallStalls < kMaxEnergyStalls;
584 };
585
586 while (!objf->isConverged() || iteration == 0) {
587 matter->pollCancel("saddle");
588
589 if (!firstIteration) {
590
591 if (params.saddle_search_options().nonlocal_count_abort != 0) {
593 initialPosition - matter->getPositions(),
594 params.saddle_search_options().nonlocal_distance_abort);
595 if (nm >= params.saddle_search_options().nonlocal_count_abort) {
597 break;
598 }
599 }
600
602 params.saddle_search_options().zero_mode_abort_curvature) {
603 QUILL_LOG_DEBUG(log, "Zero mode eigenvalue: {}",
606 break;
607 }
608 }
609 firstIteration = false;
610
611 if (iteration >= effectiveMaxIter) {
613 break;
614 }
615
616 const VectorXd posBefore = objf->getPositions();
617 AtomMatrix pos = matter->getPositions();
618
619 try {
620 if (params.saddle_search_options().confine_positive.bowl_breakout &&
622 params.optimizer_options().method == OptType::CG) {
623 optStatus = optim->step(-translationCap);
624 } else {
625 optStatus = optim->step(translationCap);
626 }
627 } catch (const eonc::DimerModeRestoredException &) {
628 QUILL_LOG_DEBUG(
629 log, "Dimer restored to best state. Checking convergence...");
630 status = objf->isConverged() ? STATUS_GOOD : STATUS_DIMER_RESTORED_BEST;
631 break;
632 } catch (const eonc::DimerModeLostException &) {
633 QUILL_LOG_WARNING(log, "Dimer lost mode completely. Aborting.");
635 break;
636 }
637
638 if (optStatus < 0) {
640 break;
641 }
642
643 double de = objf->getEnergy() - reactantEnergy;
644 const double energyLimit = params.saddle_search_options().max_energy;
645 if (de > energyLimit) {
646 const bool kept = pullUnderEnergy(posBefore);
647 if (kept) {
648 optim->onTranslationPulledBack();
649 }
650 if (!kept || objf->getEnergy() - reactantEnergy > energyLimit) {
652 // Count the attempt so a first-step abort does not fall through
653 // to the iteration == 0 mode estimate below.
654 ++iteration;
655 break;
656 }
657 de = objf->getEnergy() - reactantEnergy;
658 } else if (translationCap < stockMove) {
659 translationCap =
660 std::min(stockMove, translationCap * kMaxEnergyCapRegrowth);
661 wallStalls = 0;
662 }
663
664 // Melander, Laasonen, Jonsson, JCTC 11(3), 1055-1062, 2015
665 if (params.saddle_search_options().remove_rotation) {
667 }
668 double stepSize = (matter->pbc(matter->getPositions() - pos)).norm();
669
670 iteration++;
671
672 // Logging
677 double conv = objf->getConvergence();
678
679 if (params.saddle_search_options().minmode_method ==
681 QUILL_LOG_DEBUG(
682 log,
683 "[Lanczos] {:9} {:9.6f} {:10.4f} {:18.5e} {:9.4f} {:10.6f} "
684 "{:7.3f} {:5}\n",
685 iteration, stepSize, de, conv, eigenval, torque, angle, rotations);
686 } else {
687 QUILL_LOG_DEBUG(
688 log,
689 "[Dimer] {:9} {:9.7f} {:10.4f} {:18.5e} {:9.4f} {:7.3f} "
690 " {:6.3f} {:4}\n",
691 iteration, stepSize, de, conv, eigenval, torque, angle, rotations);
692 }
693
694 if (params.debug_options().write_movies || retain_climb_frames_) {
695 write_climb_frame(static_cast<uint64_t>(iteration), true, stepSize, de,
696 conv, eigenval, torque, angle, rotations);
697 }
698
699 if (params.main_options().checkpoint) {
700 if (!eonc::io::io_ok(
701 matter->matter2con("displacement_cp.con", false))) {
702 QUILL_LOG_WARNING(log, "Failed to write displacement_cp.con");
703 }
704 eonc::helpers::saveMode("mode_cp.dat", matter,
706 }
707
708 if (atKnownSaddle()) {
709 QUILL_LOG_DEBUG(log, "[MinModeSaddleSearch] reached a known saddle");
711 break;
712 }
713
714 // Check ImprovedDimer mode convergence
715 if (auto *dimer = eonc::asImprovedDimer(*minModeMethod)) {
716 if (!dimer->rotationDidConverge) {
717 status = (dimer->getEigenvalue() < 0.0) ? STATUS_DIMER_RESTORED_BEST
720 QUILL_LOG_DEBUG(log, "Dimer restored to valid state. C_tau={:.4f}",
721 dimer->getEigenvalue());
722 }
723 break;
724 }
725 }
726 }
727
728 // A rejected or restored mode already carries the curvature needed by
729 // the caller; solving it again would discard that handoff state.
730 if (iteration == 0 && status != STATUS_DIMER_LOST_MODE &&
733 }
734
735 // Never report STATUS_GOOD when the climb objective is unconverged
736 // (issue #20: unfeasible systems must not look like success).
737 const bool climbConverged = objf->isConverged();
738 const int statusBeforeGuard = status;
739 status = finalizeClimbStatus(status, climbConverged);
740 if (statusBeforeGuard == STATUS_GOOD && status != STATUS_GOOD) {
741 QUILL_LOG_WARNING(log, "[MinModeSaddleSearch] objective not converged; "
742 "refusing STATUS_GOOD");
743 }
744
745 long refineForceCalls = 0;
746 if (params.saddle_search_options().prfo_refine.enabled &&
747 status == STATUS_GOOD && getEigenvalue() < 0.0) {
748 const auto refined = eonc::prfoRefineSaddle(*matter, getEigenvector(),
750 refineForceCalls = refined.forceCalls;
751 if (!refined.restored) {
752 // The mode at the refined point, for mode.dat and the sign test.
754 }
755 }
756
757 if (getEigenvalue() > 0.0 && status == STATUS_GOOD) {
758 QUILL_LOG_DEBUG(log, "[MinModeSaddleSearch] eigenvalue not negative");
760 }
761 forcecalls =
763 probeForceCalls + refineForceCalls);
764 }
765
766 return status;
767}
768
769void MinModeSaddleSearch::setKnownSaddles(std::vector<AtomMatrix> positions,
770 std::vector<double> energies) {
771 if (positions.size() != energies.size()) {
772 throw std::invalid_argument(
773 "MinModeSaddleSearch::setKnownSaddles: size mismatch");
774 }
775 knownSaddlePositions_ = std::move(positions);
776 knownSaddleEnergies_ = std::move(energies);
777}
778
780 if (knownSaddleEnergies_.empty() ||
782 return false;
783 }
784 const double energy = matter->getPotentialEnergy();
785 const double eps = params.structure_comparison_options().energy_difference;
786 for (size_t k = 0; k < knownSaddleEnergies_.size(); ++k) {
787 if (std::abs(energy - knownSaddleEnergies_[k]) > eps) {
788 continue;
789 }
790 Matter known(*matter);
792 if (known.compare(*matter)) {
793 return true;
794 }
795 }
796 return false;
797}
798
802
806
807} // namespace eonc
Direct optimization for energy minimization.
double matDot(const AtomMatrix &a, const AtomMatrix &b)
SIMD-optimized dot product for contiguous Eigen matrices.
Definition Eigen.h:50
Eigen::Matrix< double, Eigen::Dynamic, 3, eOnStorageOrder > AtomMatrix
Definition Eigen.h:37
#define EONC_LOG_DEBUG(...)
Definition EonLogger.h:310
#define EONC_LOG_CRITICAL(...)
Definition EonLogger.h:334
Finds transition states by finding saddle points on the potential energy surface.
static const char MINMODE_GPRDIMER[]
static const char MINMODE_DIMER[]
static const char MINMODE_LANCZOS[]
void setPositions(const AtomMatrix &pos)
Definition Matter.cpp:420
bool compare(const Matter &matter, bool indistinguishable=false)
Definition Matter.cpp:254
~MinModeObjectiveFunction() override=default
MinModeObjectiveFunction(std::shared_ptr< Matter > matterPassed, std::shared_ptr< EigenmodeStrategy > minModeMethodPassed, AtomMatrix modePassed, double reactantEnergyPassed, const Parameters &paramsPassed)
VectorXd getGradient(bool fdstep=false)
void reseedMode(const AtomMatrix &seed)
VectorXd difference(const VectorXd &a, const VectorXd &b)
std::shared_ptr< EigenmodeStrategy > minModeMethod
std::optional< double > knownCurvature() const override
bool gradientMatchesEnergy() const override
std::shared_ptr< Matter > matter
MinModeSaddleSearch(std::shared_ptr< Matter > matterPassed, AtomMatrix modePassed, double reactantEnergyPassed, const Parameters &parametersPassed, std::shared_ptr< Potential > potPassed)
int runRetainFrames(long max_iterations_override=-1)
Like run(), but also retain climb ConFrames in memory (same stamps as write_movies climb CON).
std::vector< double > knownSaddleEnergies_
std::vector< readcon::ConFrame > climb_frames_
std::shared_ptr< Matter > matter
static constexpr int finalizeClimbStatus(int climbStatus, bool objectiveConverged) noexcept
Issue #20 policy: never leave climb as STATUS_GOOD when the climb objective is still unconverged (unf...
std::shared_ptr< EigenmodeStrategy > minModeMethod
void setKnownSaddles(std::vector< AtomMatrix > positions, std::vector< double > energies)
Saddles the server already holds for this state (positions, energies).
std::vector< AtomMatrix > knownSaddlePositions_
ObjectiveFunction(const Parameters &paramsPassed)
const Parameters & params
std::shared_ptr< Potential > pot
SaddleSearchMethod(std::shared_ptr< Potential > potPassed, const Parameters &paramsPassed)
long numAtomsMoved(const AtomMatrix v1, double cutoff)
double maxAtomMotionV(const VectorXd v1)
void rotationRemove(const AtomMatrix r1, std::shared_ptr< Matter > m2)
std::unique_ptr< Optimizer > mkOptim(std::shared_ptr< ObjectiveFunction > a_objf, OptType a_otype, const Parameters &a_params)
Definition Optimizer.cpp:55
void saveMode(FILE *modeFile, std::shared_ptr< Matter > matter, AtomMatrix mode)
Write a mode; constrained axes are emitted as 0.
void requireKnownConvergenceMetric(std::string_view metric, std::string_view context)
Throws std::invalid_argument naming context when metric is unrecognized.
readcon::ConFrame matterToConFrame(Matter &m, const ConFrameMetadata *metadata)
Build a single stamped ConFrame from Matter (same builder as matter2con).
constexpr bool io_ok(IoStatus s) noexcept
Definition ConFileIO.h:38
RAII resource manager for the ARTn C library with global synchronization.
void eigenmodeCompute(LowestEigenmode &s, std::shared_ptr< Matter > matter, AtomMatrix direction)
PrfoRefineResult prfoRefineSaddle(Matter &, const AtomMatrix &, double, const Parameters &)
Partitioned rational function optimization (P-RFO) of a first-order saddle in the rgsaddle Sella orde...
long eigenmodeTotalForceCalls(LowestEigenmode &s)
std::shared_ptr< LowestEigenmode > buildEigenmodeStrategy(std::shared_ptr< Matter > matter, const Parameters &params, std::shared_ptr< Potential > pot)
long eigenmodeStatsRotations(LowestEigenmode &s)
ImprovedDimer * asImprovedDimer(LowestEigenmode &s)
long eigenmodeTotalIterations(LowestEigenmode &s)
double eigenmodeGetEigenvalue(LowestEigenmode &s)
double eigenmodeStatsTorque(LowestEigenmode &s)
AtomMatrix eigenmodeGetEigenvector(LowestEigenmode &s)
double eigenmodeStatsAngle(LowestEigenmode &s)
void requirePrfoRefine(const Parameters &params)
Does nothing unless [Saddle Search] prfo_refine is on.
std::optional< uint64_t > frame_index
Definition ConFileIO.h:72
std::vector< ConMetadataValue > scalars
Definition ConFileIO.h:79
std::optional< double > energy
Definition ConFileIO.h:73