Loading...
Searching...
No Matches
VibrationalIndexGate.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
6
7#include <fstream>
8#include <iostream>
9#include <map>
10#include <sstream>
11#include <utility>
12
17
18namespace gpr::neb {
19namespace {
20
21struct Frame {
22 Eigen::VectorXd masses;
23 Eigen::VectorXi frozen;
24 const Eigen::VectorXi* frozen_ptr = nullptr;
25 bool anchored = false;
26 bool periodic = false;
27 bool usable = false;
28};
29
33Eigen::MatrixXd stencilDirections(const Frame& frame,
34 const Eigen::VectorXd& positions,
36{
37 return gpr::optim::stencilDirectionsForMode(mode, positions, frame.masses,
38 frame.periodic, frame.anchored,
39 frame.frozen_ptr);
40}
41
42Frame frameFor(const Eigen::VectorXd& positions,
43 const gpr::AtomsConfiguration* atoms)
44{
45 Frame frame;
46 const Eigen::Index dof = positions.size();
47 if (dof <= 0 || dof % 3 != 0 || !positions.allFinite()) return frame;
48 const Eigen::Index n_here = dof / 3;
49 frame.masses = Eigen::VectorXd::Ones(n_here);
50 if (atoms == nullptr) {
51 frame.usable = true;
52 return frame;
53 }
54 const Eigen::Index n_total = atoms->is_frozen.size();
55 bool any_frozen = false;
56 if (n_total > 0) {
57 for (Eigen::Index atom = 0; atom < n_total; ++atom) {
58 if (*(atoms->is_frozen.data() + atom) != MOVING_ATOM)
59 any_frozen = true;
60 }
61 }
62 try {
63 if (any_frozen && n_here < n_total) {
64 frame.masses = gpr::optim::movingAtomicMasses(*atoms, n_here);
65 frame.anchored = true;
66 } else if (atoms->atomic_masses.size() == n_here) {
67 frame.masses = atoms->atomic_masses;
68 } else if (n_total == n_here &&
69 atoms->atomic_masses.size() == n_total) {
70 frame.masses = atoms->atomic_masses;
71 }
72 } catch (const std::invalid_argument&) {
73 frame.masses = Eigen::VectorXd::Ones(n_here);
74 }
75 if (frame.masses.size() != n_here || !frame.masses.allFinite() ||
76 (frame.masses.array() <= 0.0).any()) {
77 frame.masses = Eigen::VectorXd::Ones(n_here);
78 }
79 if (any_frozen && n_here == n_total) {
80 frame.frozen.resize(n_here);
81 for (Eigen::Index atom = 0; atom < n_here; ++atom) {
82 frame.frozen(atom) =
83 *(atoms->is_frozen.data() + atom) == MOVING_ATOM ? 0 : 1;
84 }
85 frame.frozen_ptr = &frame.frozen;
86 }
87 frame.periodic = gpr::geometry::cellIsMicLattice(atoms->cell);
88 frame.usable = true;
89 return frame;
90}
91
92Eigen::MatrixXd surrogateHessian(gpr::GaussianProcessRegression& gp,
93 const Eigen::VectorXd& positions)
94{
95 Eigen::MatrixXd hessian;
96 if (!gp.calculateMeanHessian(positions.transpose(), hessian)) return {};
97 return hessian;
98}
99
100double energyVariance(gpr::GaussianProcessRegression& gp,
101 const Eigen::VectorXd& positions)
102{
103 gpr::Observation probe;
104 probe.R.resize(1, positions.size());
105 probe.R.row(0) = positions.transpose();
107 return probe.E.size() > 0 ? probe.E(0, 0)
108 : std::numeric_limits<double>::infinity();
109}
110
111VibrationalIndexDecision fromMeasurement(
112 const VibrationalIndexMeasurement& measured, const char* source,
113 int true_calls, double variance, double threshold)
114{
116 decision.checked = measured.measured;
117 decision.accept = measured.measured && measured.pass;
118 decision.source = source;
119 decision.true_calls = true_calls;
120 decision.negative = measured.negative;
121 decision.unresolved = measured.unresolved;
122 decision.resolution = measured.resolution;
123 decision.curvatures = measured.curvatures;
124 decision.variance = variance;
125 decision.variance_threshold = threshold;
126 decision.step = measured.step;
127 return decision;
128}
129
130} // namespace
131
132Eigen::MatrixXd oracleStencilDirections(const Eigen::VectorXd& positions,
133 const gpr::AtomsConfiguration* atoms,
135{
136 const Frame frame = frameFor(positions, atoms);
137 if (!frame.usable)
138 throw std::invalid_argument("invalid geometry for an oracle stencil");
139 return stencilDirections(frame, positions, stencil);
140}
141
143 const Eigen::VectorXd& positions, const Eigen::VectorXd& gradient,
145 double variance, double variance_threshold, double move,
146 double stencil_step, const NEBOracle* oracle, const NEBBatchOracle* batch,
147 Eigen::Index batch_chunk, gpr::optim::VibrationalStencil stencil)
148{
150 const Frame frame = frameFor(positions, atoms);
151 if (!frame.usable) return decision;
152 const Eigen::VectorXd* gradient_ptr =
153 gradient.size() == positions.size() && gradient.allFinite() ? &gradient
154 : nullptr;
155 auto classify = [&](const Eigen::MatrixXd& columns, const char* source,
156 int true_calls,
157 const Eigen::MatrixXd* measured = nullptr) {
158 return fromMeasurement(
159 indexFromCartesianColumns(columns, positions, frame.masses, move,
160 gradient_ptr, frame.frozen_ptr,
161 frame.anchored, measured),
162 source, true_calls, variance, variance_threshold);
163 };
164
165 // The mean Hessian screens the point. Posterior energy variance above
166 // the caller's threshold, or three or more negative surrogate modes,
167 // is the only reason to buy a true stencil. A resolved index-1
168 // surrogate accepts. Two surrogate negatives, or none, are the hollow
169 // adatom's false reading of a true index-1 saddle: they neither spend
170 // true calls nor withdraw the converged claim.
171 //
172 // The band row is every atom in file order. The kernel reads that row
173 // as atoms_mov. A session that never loaded a geometry (standard and
174 // AIE leave the GP uninitialised) has an empty moving set, and a
175 // derivative channel then indexes past it. Skip the surrogate and
176 // screen on the true surface instead of throwing.
177 const bool surrogate_geometry =
178 gp != nullptr && atoms != nullptr && atoms->atoms_mov.type.size() > 0 &&
179 3 * atoms->atoms_mov.type.size() == positions.size();
180 if (surrogate_geometry) {
181 if (!std::isfinite(variance)) variance = energyVariance(*gp, positions);
182 const bool uncertain =
183 !std::isfinite(variance) || variance > variance_threshold;
184 const Eigen::MatrixXd hessian = surrogateHessian(*gp, positions);
185 if (hessian.rows() == positions.size() && hessian.allFinite()) {
186 auto surrogate = classify(hessian, "surrogate", 0);
187 std::cout << "[neb] vibrational index: source=surrogate"
188 << " negative=" << surrogate.negative
189 << " unresolved=" << surrogate.unresolved
190 << " resolution=" << surrogate.resolution
191 << " variance=" << variance
192 << " threshold=" << variance_threshold << " true_calls=0"
193 << " pass=" << (surrogate.accept ? "yes" : "no") << "\n";
194 if (surrogate.checked && !uncertain && surrogate.unresolved == 0 &&
195 surrogate.negative <= 2) {
196 // A resolved index-1 surrogate is the decision. Zero, one,
197 // or two negatives under the variance threshold are not a
198 // refutation: the hollow adatom's mean Hessian reports two
199 // or none at a true index-1 saddle. Leave the converged
200 // claim in place and spend no true calls.
201 surrogate.checked = true;
202 surrogate.accept = true;
203 return surrogate;
204 }
205 }
206 }
207
208 if (oracle == nullptr || !(stencil_step > 0.0) ||
209 !std::isfinite(stencil_step)) {
210 decision.checked = false;
211 return decision;
212 }
213 // A free molecule whose coordinates are pure rigid motion has no
214 // vibrational index. Leave the caller's convergence claim unchanged
215 // and spend no true evaluations. Full still measures every coordinate.
217 !frame.anchored && frame.frozen_ptr == nullptr &&
218 gpr::optim::vibrationalComplement(positions, frame.masses).cols() ==
219 0) {
220 decision.checked = false;
221 return decision;
222 }
223 const Eigen::MatrixXd directions =
224 stencilDirections(frame, positions, stencil);
225 CartesianOracleStencil oracle_stencil;
226 if (gradient_ptr != nullptr) {
227 const CartesianOracleCenter center{positions, 0.0, gradient};
228 oracle_stencil =
229 evaluateCartesianOracleStencil(positions, stencil_step, directions,
230 *oracle, center, batch, batch_chunk);
231 } else {
232 oracle_stencil = evaluateCartesianOracleStencil(
233 positions, stencil_step, directions, *oracle, batch, batch_chunk);
234 }
235 int true_calls = 0;
236 if (!oracle_stencil.complete()) return decision;
237 // The center column is reused when a gradient was supplied. Every
238 // other column is one displaced force evaluation.
239 true_calls = static_cast<int>(oracle_stencil.positions.cols() -
240 (gradient_ptr ? 1 : 0));
241 const Eigen::MatrixXd columns = stencilHessianColumns(oracle_stencil);
242 if (columns.rows() != positions.size()) return decision;
243 const auto measured = indexFromCartesianColumns(
244 columns, positions, frame.masses, move, gradient_ptr, frame.frozen_ptr,
245 frame.anchored, &oracle_stencil.directions);
246 auto truth = fromMeasurement(measured, "true", true_calls, variance,
247 variance_threshold);
248 std::cout << "[neb] vibrational index: source=true"
249 << " negative=" << truth.negative
250 << " unresolved=" << truth.unresolved
251 << " resolution=" << truth.resolution
252 << " true_calls=" << truth.true_calls
253 << " pass=" << (truth.accept ? "yes" : "no") << " eigenvalues=[";
254 for (Eigen::Index i = 0; i < measured.curvatures.size(); ++i) {
255 if (i > 0) std::cout << ",";
256 std::cout << measured.curvatures(i);
257 }
258 std::cout << "]\n";
259 return truth;
260}
261
263 const VibrationalIndexDecision& decision,
264 int outer_budget)
265{
266 if (!result.converged || !result.path) return;
267 result.index_checked = decision.checked;
268 result.index_negative = decision.negative;
269 result.index_unresolved = decision.unresolved;
270 result.index_resolution = decision.resolution;
271 result.index_gate_true_calls += decision.true_calls;
272 result.oracle_calls += decision.true_calls;
273 result.oracle_calls_outer += decision.true_calls;
274 result.index_continue = false;
275 if (!decision.checked) return;
276 if (decision.accept) return;
277 const int image = result.max_energy_image;
278 auto& path = *result.path;
279 const bool interior = image > 0 && image < path.numImages() - 1;
280 const bool budget_left =
281 result.outer_iterations < outer_budget && interior &&
282 decision.step.size() == path.image(image).positions.size() &&
283 decision.step.allFinite();
284 result.converged = false;
286 if (!budget_left) {
287 result.index_refused = true;
288 std::cout << "[neb] vibrational index: action=refuse"
289 << " negative=" << decision.negative
290 << " unresolved=" << decision.unresolved
291 << " outer=" << result.outer_iterations
292 << " budget=" << outer_budget << "\n";
293 return;
294 }
295 path.image(image).positions += decision.step;
296 path.image(image).evaluated = false;
297 result.index_continue = true;
298 std::cout << "[neb] vibrational index: action=continue"
299 << " negative=" << decision.negative
300 << " unresolved=" << decision.unresolved
301 << " step=" << decision.step.norm()
302 << " outer=" << result.outer_iterations
303 << " budget=" << outer_budget << "\n";
304}
305
306namespace {
307
308struct StencilRecord {
310 VibrationalIndexMeasurement index;
311 CartesianOracleStencil stencil;
312};
313
314std::map<std::string, StencilRecord> stencil_cache;
315
316std::string geometryKey(const Eigen::VectorXd& center,
318{
319 std::ostringstream out;
320 out.setf(std::ios::fixed);
321 out.precision(8);
322 for (Eigen::Index i = 0; i < center.size(); ++i) {
323 if (i) out << ',';
324 out << center(i);
325 }
326 out << (mode == gpr::optim::VibrationalStencil::Vibrational ? "|v" : "|f");
327 return out.str();
328}
329
330} // namespace
331
333{
334 stencil_cache.clear();
335}
336
337void writeForceStopHandoff(const std::string& archive_dir,
338 const GPNEBResult& result)
339{
340 if (archive_dir.empty() || !result.force_stop_hand_off) return;
341 std::ofstream out(archive_dir + "/force-stop-handoff.bin",
342 std::ios::binary);
343 if (!out) return;
344 // 0x46534832 carries the deferred flag and the lowest modes.
345 // 0x46534831 was positions and gradients only.
346 const int magic = 0x46534832;
347 const int dof = static_cast<int>(result.force_stop_positions.rows());
348 const int npts = static_cast<int>(result.force_stop_positions.cols());
349 const int nmodes =
350 result.force_stop_modes.rows() == result.force_stop_positions.rows()
351 ? static_cast<int>(result.force_stop_modes.cols())
352 : 0;
353 int flags = 0;
354 if (!result.force_stop_deferred && !result.force_stop_inconclusive &&
355 !result.force_stop_certified)
356 flags |= 1;
357 if (result.force_stop_inconclusive) flags |= 2;
358 if (result.force_stop_deferred) flags |= 4;
359 out.write(reinterpret_cast<const char*>(&magic), sizeof magic);
360 out.write(reinterpret_cast<const char*>(&dof), sizeof dof);
361 out.write(reinterpret_cast<const char*>(&npts), sizeof npts);
362 out.write(reinterpret_cast<const char*>(&nmodes), sizeof nmodes);
363 out.write(reinterpret_cast<const char*>(&result.force_stop_displacement),
364 sizeof result.force_stop_displacement);
365 out.write(reinterpret_cast<const char*>(&flags), sizeof flags);
366 if (npts > 0 && dof > 0) {
367 out.write(
368 reinterpret_cast<const char*>(result.force_stop_positions.data()),
369 sizeof(double) * result.force_stop_positions.size());
370 out.write(
371 reinterpret_cast<const char*>(result.force_stop_gradients.data()),
372 sizeof(double) * result.force_stop_gradients.size());
373 }
374 const int nenergy = static_cast<int>(result.force_stop_energies.size());
375 out.write(reinterpret_cast<const char*>(&nenergy), sizeof nenergy);
376 if (nenergy > 0)
377 out.write(
378 reinterpret_cast<const char*>(result.force_stop_energies.data()),
379 sizeof(double) * nenergy);
380 if (nmodes > 0)
381 out.write(reinterpret_cast<const char*>(result.force_stop_modes.data()),
382 sizeof(double) * static_cast<std::size_t>(dof * nmodes));
383}
384
385std::optional<ForceStopHandoffStencil> readForceStopHandoff(
386 const std::string& archive_dir, const Eigen::VectorXd& center)
387{
388 if (archive_dir.empty() || center.size() == 0) return std::nullopt;
389 std::ifstream in(archive_dir + "/force-stop-handoff.bin", std::ios::binary);
390 if (!in) return std::nullopt;
391 int magic = 0, dof = 0, npts = 0, flags = 0, nenergy = 0, nmodes = 0;
392 double step = 0.0;
393 in.read(reinterpret_cast<char*>(&magic), sizeof magic);
394 in.read(reinterpret_cast<char*>(&dof), sizeof dof);
395 in.read(reinterpret_cast<char*>(&npts), sizeof npts);
396 const bool version2 = magic == 0x46534832;
397 if (version2) in.read(reinterpret_cast<char*>(&nmodes), sizeof nmodes);
398 in.read(reinterpret_cast<char*>(&step), sizeof step);
399 in.read(reinterpret_cast<char*>(&flags), sizeof flags);
400 if (!in || (magic != 0x46534831 && magic != 0x46534832) || dof < 0 ||
401 npts < 0 || nmodes < 0)
402 return std::nullopt;
404 stencil.step = step;
405 stencil.higher_order = (flags & 1) != 0;
406 stencil.inconclusive = (flags & 2) != 0;
407 stencil.deferred = version2 && (flags & 4) != 0;
408 if (stencil.deferred && npts == 0) return stencil;
409 if (dof != center.size() || npts <= 0 || dof <= 0) return std::nullopt;
410 stencil.positions.resize(dof, npts);
411 stencil.gradients.resize(npts, dof);
412 in.read(reinterpret_cast<char*>(stencil.positions.data()),
413 sizeof(double) * stencil.positions.size());
414 in.read(reinterpret_cast<char*>(stencil.gradients.data()),
415 sizeof(double) * stencil.gradients.size());
416 in.read(reinterpret_cast<char*>(&nenergy), sizeof nenergy);
417 if (nenergy > 0) {
418 stencil.energies.resize(static_cast<std::size_t>(nenergy));
419 in.read(reinterpret_cast<char*>(stencil.energies.data()),
420 sizeof(double) * static_cast<std::size_t>(nenergy));
421 }
422 if (version2 && nmodes > 0) {
423 stencil.lowest_modes.resize(dof, nmodes);
424 in.read(reinterpret_cast<char*>(stencil.lowest_modes.data()),
425 sizeof(double) * stencil.lowest_modes.size());
426 }
427 if (!in || stencil.positions.cols() < 1) return std::nullopt;
428 stencil.center = stencil.positions.col(0);
429 Eigen::MatrixXd held_center(stencil.center.size(), 1);
430 held_center.col(0) = stencil.center;
431 if (gpr::optim::forceStopHeldColumn(held_center, center) < 0)
432 return std::nullopt;
433 return stencil;
434}
435
437 const ForceStopHandoffStencil& handoff)
438{
439 if (handoff.positions.cols() == 0 || handoff.gradients.rows() == 0)
440 return 0;
441 const Eigen::Index dof = handoff.positions.rows();
442 if (handoff.gradients.cols() != dof) return 0;
443 if (observations.R.cols() != 0 && observations.R.cols() != dof) return 0;
444 int added = 0;
445 for (Eigen::Index col = 0; col < handoff.positions.cols(); ++col) {
446 if (col >= handoff.gradients.rows()) break;
447 const Eigen::VectorXd position = handoff.positions.col(col);
448 const Eigen::VectorXd gradient = handoff.gradients.row(col).transpose();
449 if (!position.allFinite() || !gradient.allFinite()) continue;
450 if (gpr::optim::forceStopHeldColumn(observations.R.transpose(),
451 position) >= 0)
452 continue;
453 const Eigen::Index row = observations.R.rows();
454 observations.R.conservativeResize(row + 1, dof);
455 observations.E.conservativeResize(row + 1, 1);
456 observations.G.conservativeResize(row + 1, dof);
457 observations.R.row(row) = position.transpose();
458 observations.E(row, 0) =
459 col < static_cast<Eigen::Index>(handoff.energies.size())
460 ? handoff.energies[static_cast<std::size_t>(col)]
461 : 0.0;
462 observations.G.row(row) = gradient.transpose();
463 ++added;
464 }
465 return added;
466}
467
469 const ForceStopHandoffStencil& handoff)
470{
471 if (orient.rows() != 1 || handoff.lowest_modes.cols() < 1 ||
472 handoff.lowest_modes.rows() != orient.cols())
473 return false;
474 Eigen::VectorXd mode = handoff.lowest_modes.col(0);
475 if (!mode.allFinite() || !(mode.norm() > 0.0)) return false;
476 mode.normalize();
477 orient.row(0) = mode.transpose();
478 return true;
479}
480
482 const GPNEBConfig& config,
483 const gpr::AtomsConfiguration* atoms)
484{
485 if (!config.force_stop_certificate) return;
486 if (!result.converged || !result.path) return;
487 const int image = result.max_energy_image;
488 NEBPath& path = *result.path;
489 if (image <= 0 || image >= path.numImages() - 1) return;
490 auto& climbing = path.image(image);
491 if (!climbing.evaluated || !std::isfinite(path.saddleForce(image)) ||
492 !(path.saddleForce(image) < config.conv_tol))
493 return;
494 const double step =
496 const gpr::optim::VibrationalStencil stencil_mode =
497 config.vibrational_stencil;
498 const Frame frame = frameFor(climbing.positions, atoms);
499 if (!frame.usable) return;
502 query.requested = config.force_stop_certificate;
505 stencil_cache.find(geometryKey(climbing.positions, stencil_mode)) !=
506 stencil_cache.end();
509 if (plan.defer_certificate) {
510 const auto outcome = gpr::optim::runForceStopCertificate(
511 [] { return gpr::optim::ForceStopMeasurement{}; },
512 [] { return -1; }, plan);
513 result.force_stop_certificate_calls = outcome.calls;
514 result.force_stop_certified = false;
515 result.force_stop_hand_off = outcome.hand_off;
516 result.force_stop_deferred = outcome.deferred_to_following_stage;
517 result.index_checked = false;
518 result.index_continue = false;
519 result.index_refused = false;
520 std::cout << "[neb] force-stop stencil: deferred to the saddle stage\n";
521 return;
522 }
525 const Eigen::VectorXd stopped_at = climbing.positions;
526 // A resumed band arrives with the calls of its earlier certificates.
527 const int earlier_calls = result.force_stop_certificate_calls;
528 const auto measure_once = [&]() {
530 const Eigen::VectorXd center = climbing.positions;
531 const std::string key = geometryKey(center, stencil_mode);
532 const auto cached = stencil_cache.find(key);
533 if (cached != stencil_cache.end()) {
534 latest = cached->second.index;
535 stencil = cached->second.stencil;
536 measured = cached->second.measurement;
537 measured.calls = 0;
538 std::cout << "[neb] force-stop stencil: cached geometry"
539 << " negative=" << latest.negative
540 << " first_order=" << measured.first_order
541 << " higher_order=" << measured.higher_order << "\n";
542 return measured;
543 }
544 const bool reuse = climbing.gradient.size() == center.size() &&
545 climbing.gradient.allFinite() &&
546 std::isfinite(climbing.energy);
547 const Eigen::MatrixXd directions =
548 stencilDirections(frame, center, stencil_mode);
549 if (reuse) {
550 const CartesianOracleCenter held{center, climbing.energy,
551 climbing.gradient};
553 center, step, directions, oracle, held, &config.batch_oracle,
554 config.oracle_batch_chunk);
555 } else {
557 center, step, directions, oracle, &config.batch_oracle,
558 config.oracle_batch_chunk);
559 }
560 measured.calls = stencil.complete()
561 ? static_cast<int>(stencil.positions.cols() -
562 (stencil.center_reused ? 1 : 0))
563 : 0;
564 const Eigen::MatrixXd columns = stencilHessianColumns(stencil);
565 if (columns.rows() == center.size() && frame.usable) {
566 const Eigen::VectorXd* gradient =
567 reuse ? &climbing.gradient : nullptr;
569 columns, center, frame.masses, step, gradient, frame.frozen_ptr,
570 frame.anchored, &stencil.directions);
571 measured.measured = latest.measured;
572 measured.first_order = latest.pass;
573 measured.higher_order = latest.negative > 1;
574 }
575 std::cout << "[neb] force-stop stencil: negative=" << latest.negative
576 << " unresolved=" << latest.unresolved
577 << " calls=" << measured.calls
578 << " first_order=" << measured.first_order
579 << " higher_order=" << measured.higher_order << "\n";
580 stencil_cache[key] = StencilRecord{measured, latest, stencil};
581 return measured;
582 };
583 // A following saddle owns an inconclusive or higher-order stencil.
584 // The columns were already paid for: hand them over and do not
585 // measure again. The final stage still refines, then certifies.
587 if (config.saddle_stage_follows) {
588 const auto cached =
589 stencil_cache.find(geometryKey(climbing.positions, stencil_mode));
591 if (cached != stencil_cache.end()) {
592 prior = cached->second.measurement;
593 prior.calls = 0;
594 stencil = cached->second.stencil;
595 latest = cached->second.index;
596 const Eigen::MatrixXd columns = stencilHessianColumns(stencil);
597 if (columns.rows() == climbing.positions.size() &&
598 frame.masses.size() * 3 == climbing.positions.size()) {
599 prior.hessian = columns;
601 columns, climbing.positions, frame.masses, 4,
602 &stencil.directions);
603 prior.positions = stencil.positions;
604 prior.gradients = stencil.observations.gradient;
605 prior.center = climbing.positions;
606 prior.step = step;
607 }
608 }
610 measure_once, [] { return -1; }, plan, &prior);
611 } else {
613 measure_once,
614 [&]() {
615 if (latest.step.size() != climbing.positions.size() ||
616 !latest.step.allFinite())
617 return -1;
618 climbing.positions += latest.step;
619 const auto sample = oracle(climbing.positions);
620 if (!std::isfinite(sample.first) ||
621 sample.second.size() != climbing.positions.size() ||
622 !sample.second.allFinite())
623 return -1;
624 climbing.energy = sample.first;
625 climbing.gradient = sample.second;
626 climbing.evaluated = true;
627 std::cout << "[neb] force-stop stencil: one soft-mode step\n";
628 return 1;
629 },
630 plan);
631 // The soft-mode steps stay inside the negative well. Leave along
632 // the extra negative mode, doubling the displacement, and certify
633 // the point that is reached. A following saddle does this itself.
634 double length = latest.step.norm();
635 Eigen::VectorXd direction =
636 latest.step.size() == climbing.positions.size() && length > 0.0
637 ? latest.step / length
638 : Eigen::VectorXd();
639 for (int escape = 0; outcome.needs_min_mode_escape &&
641 direction.size() == climbing.positions.size();
642 ++escape) {
643 length *= 2.0;
644 const Eigen::VectorXd trial =
645 climbing.positions + length * direction;
646 const auto sample = oracle(trial);
647 if (!std::isfinite(sample.first) ||
648 sample.second.size() != trial.size() ||
649 !sample.second.allFinite())
650 break;
651 climbing.positions = trial;
652 climbing.energy = sample.first;
653 climbing.gradient = sample.second;
654 climbing.evaluated = true;
655 std::cout << "[neb] force-stop stencil: min-mode escape\n";
656 const gpr::optim::ForceStopMeasurement measured = measure_once();
657 outcome.calls += measured.calls + 1;
658 outcome.measurements += 1;
659 outcome.measured = measured.measured;
660 outcome.higher_order = measured.higher_order;
661 outcome.first_order = measured.measured && measured.first_order &&
662 !measured.higher_order;
664 measured.measured, outcome.first_order);
665 outcome.needs_min_mode_escape = measured.measured &&
666 measured.higher_order &&
667 !outcome.certified;
668 // Keep the grown length. The new stencil's step is one finite
669 // difference, and resetting to it walks in place.
670 if (latest.step.size() == direction.size() &&
671 latest.step.norm() > 0.0)
672 direction = latest.step / latest.step.norm();
673 }
674 }
675 result.force_stop_certificate_calls = earlier_calls + outcome.calls;
676 result.oracle_calls += outcome.calls;
677 result.oracle_calls_validation += outcome.calls;
678 // The soft-mode and escape steps move the climbing image and measure
679 // it. The force stop held at the geometry the band stopped on, not at
680 // the one those steps reached: a first-order index there does not make
681 // it stationary. Report its measured force, and when that is above the
682 // tolerance give the stepped band back to the search.
683 if (!config.saddle_stage_follows && climbing.evaluated &&
684 (climbing.positions - stopped_at).norm() > 0.0) {
685 const double force = path.saddleForce(image);
686 result.returned_true_force = force;
687 if (!(std::isfinite(force) && force < config.conv_tol)) {
688 std::cout << "[neb] force-stop stencil: the stepped image has"
689 << " force=" << force
690 << " above tolerance=" << config.conv_tol
691 << "; the band resumes\n";
692 result.force_stop_certified = false;
693 result.index_checked = outcome.measured;
694 result.index_negative = latest.negative;
695 result.index_unresolved = latest.unresolved;
696 result.index_resolution = latest.resolution;
697 result.index_refused = false;
698 result.index_continue = true;
699 result.converged = false;
701 return;
702 }
703 }
704 result.force_stop_certified = outcome.certified;
705 result.force_stop_positions = stencil.positions;
706 result.force_stop_directions = stencil.directions;
707 result.force_stop_gradients = stencil.observations.gradient;
708 result.force_stop_energies = Eigen::Map<const Eigen::VectorXd>(
709 stencil.observations.energy.data(),
710 static_cast<Eigen::Index>(stencil.observations.energy.size()));
711 result.force_stop_displacement = stencil.displacement;
713 result.force_stop_wall_s = stencil.wall_seconds;
714 result.force_stop_modes = outcome.handed.lowest_modes;
716 outcome.measured && !outcome.first_order && !outcome.higher_order;
717 result.index_checked = outcome.measured;
718 result.index_negative = latest.negative;
719 result.index_unresolved = latest.unresolved;
720 result.index_resolution = latest.resolution;
721 result.index_continue = false;
722 result.force_stop_hand_off = outcome.hand_off;
723 if (config.saddle_stage_follows && outcome.measured && !outcome.certified &&
724 (outcome.higher_order || result.force_stop_inconclusive))
725 result.force_stop_hand_off = true;
726 // The band is the final stage. A higher-order stencil that the soft
727 // refinement did not repair is not a saddle. Zero negatives is not
728 // that refusal. A following saddle keeps the force stop and receives
729 // the climbing image instead.
730 result.index_refused = !result.force_stop_hand_off && outcome.measured &&
731 outcome.higher_order && !outcome.certified;
732 if (result.index_refused) {
733 result.converged = false;
735 }
736 // The same adaptive certificate the dimer uses. A final-stage band
737 // records its probes so the written stencil carries the index evidence.
738 // A following saddle owns that measurement and must not repeat it.
739 const Eigen::MatrixXd final_columns =
740 !config.saddle_stage_follows && !result.force_stop_deferred &&
741 frame.usable &&
742 frame.masses.size() * 3 == climbing.positions.size()
743 ? stencilHessianColumns(stencil)
744 : Eigen::MatrixXd();
745 if (final_columns.rows() == climbing.positions.size()) {
746 const Eigen::MatrixXd& columns = final_columns;
747 const auto index = gpr::optim::analyzeStencilIndex(
748 columns, climbing.positions, frame.masses, &stencil.directions);
749 int probes = 0;
750 const auto gradients = [&](const Eigen::MatrixXd& points) {
751 probes += static_cast<int>(points.cols());
752 Eigen::MatrixXd measured(points.cols(), points.rows());
753 for (Eigen::Index j = 0; j < points.cols(); ++j) {
754 const auto sample = oracle(points.col(j));
755 if (!std::isfinite(sample.first) ||
756 sample.second.size() != points.rows() ||
757 !sample.second.allFinite())
758 return Eigen::MatrixXd();
759 measured.row(j) = sample.second.transpose();
760 }
761 return measured;
762 };
763 const auto certificate = gpr::optim::certifyAdaptiveStencilIndex(
764 index, climbing.positions, frame.masses, step, gradients);
765 result.force_stop_certificate_calls += probes;
766 result.oracle_calls += probes;
767 result.oracle_calls_validation += probes;
768 if (certificate.refinement_points.cols() > 0 &&
769 certificate.refinement_gradients.rows() ==
770 certificate.refinement_points.cols()) {
772 certificate.refinement_points.transpose();
774 certificate.refinement_gradients;
775 result.force_stop_negative_upper = certificate.negative_upper;
776 result.force_stop_positive_lower = certificate.positive_lower;
778 certificate.negative_pair_upper;
779 result.force_stop_refinement_recorded = true;
781 certificate.higher_order;
782 result.force_stop_certified =
783 certificate.first_order && !certificate.higher_order;
784 // The coarse stencil may be unresolved. A later bound that
785 // fixes the index replaces that flag, so the summary and the
786 // file do not keep calling a resolved saddle unresolved.
787 if (result.force_stop_certified || certificate.higher_order)
788 result.force_stop_inconclusive = false;
789 if (certificate.higher_order && !certificate.first_order &&
790 !result.force_stop_hand_off) {
791 result.index_refused = true;
792 result.converged = false;
793 result.convergence_status =
795 }
796 }
797 }
798}
799
800int vibrationalIndexOuterBudget(const GPNEBConfig& config, int n_images)
801{
802 if (config.outer_budget_per_image && n_images > 0) {
803 const long cap = static_cast<long>(config.max_outer_iter) * n_images;
804 return static_cast<int>(
805 std::min<long>(cap, std::numeric_limits<int>::max()));
806 }
807 return config.max_outer_iter;
808}
809
810} // namespace gpr::neb
@ MOVING_ATOM
Definition Enums.h:35
void calculateVarianceDispatched(Observation &image1)
bool calculateMeanHessian(const Coord &R, Eigen::MatrixXd &hessian)
Dense Hessian of the physical posterior mean at one geometry.
NEB path: chain of images between two endpoints.
Definition NEBPath.h:57
int numImages() const
Definition NEBPath.h:338
Image & image(int i)
Access image i.
Definition NEBPath.h:329
double saddleForce(int i) const
Definition NEBPath.h:263
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
bool cellIsMicLattice(const double cell[9]) noexcept
Nonzero ASE 3x3 that is not the 25 A vacuum convention.
Definition MinImage.h:56
Half measured(const GradientOracle &oracle, const Eigen::VectorXd &x, Kind kind, const Options &options)
Full central difference of the oracle gradient: 2 d calls.
The nudged elastic band: path, GP-NEB driver, configuration and result, acquisition,...
std::function< std::vector< std::pair< double, Eigen::VectorXd > >( const std::vector< Eigen::VectorXd > &positions)> NEBBatchOracle
Definition GPNEB.h:89
int vibrationalIndexOuterBudget(const GPNEBConfig &config, int n_images)
Outer-iteration cap, including the per-image reading.
VibrationalIndexDecision decideVibrationalIndex(const Eigen::VectorXd &positions, const Eigen::VectorXd &gradient, const gpr::AtomsConfiguration *atoms, gpr::GaussianProcessRegression *gp, double variance, double variance_threshold, double move, double stencil_step, const NEBOracle *oracle, const NEBBatchOracle *batch, Eigen::Index batch_chunk, gpr::optim::VibrationalStencil stencil)
std::function< std::pair< double, Eigen::VectorXd >( const Eigen::VectorXd &positions)> NEBOracle
Oracle function: positions -> (energy, gradient).
Definition GPNEB.h:82
bool seedDimerModeFromForceStop(gpr::Coord &orient, const ForceStopHandoffStencil &handoff)
void writeForceStopHandoff(const std::string &archive_dir, const GPNEBResult &result)
int appendForceStopObservations(gpr::Observation &observations, const ForceStopHandoffStencil &handoff)
std::optional< ForceStopHandoffStencil > readForceStopHandoff(const std::string &archive_dir, const Eigen::VectorXd &center)
CartesianOracleStencil evaluateCartesianOracleStencil(const Eigen::VectorXd &center, double displacement, const Eigen::MatrixXd &directions, const Oracle &oracle, const NEBBatchOracle *batch_oracle=nullptr, Eigen::Index batch_chunk=0)
VibrationalIndexMeasurement indexFromCartesianColumns(const Eigen::MatrixXd &columns, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double move, const Eigen::VectorXd *center_gradient=nullptr, const Eigen::VectorXi *frozen=nullptr, bool anchored=false, const Eigen::MatrixXd *measured=nullptr)
Eigen::MatrixXd stencilHessianColumns(const CartesianOracleStencil &stencil)
void resetForceStopStencilCache()
void applyVibrationalIndexDecision(GPNEBResult &result, const VibrationalIndexDecision &decision, int outer_budget)
void certifyForceStoppedNeb(GPNEBResult &result, NEBOracle &oracle, const GPNEBConfig &config, const gpr::AtomsConfiguration *atoms)
Eigen::MatrixXd oracleStencilDirections(const Eigen::VectorXd &positions, const gpr::AtomsConfiguration *atoms, gpr::optim::VibrationalStencil stencil)
constexpr double stencilStepOrDefault(double requested) noexcept
The requested stencil step, or the default when none was requested.
StencilIndexCertificate certifyAdaptiveStencilIndex(const StencilIndex &index, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, double step, const Gradients &gradients, double noise_multiplier=0.0)
Eigen::Index forceStopHeldColumn(const Eigen::MatrixXd &held, const Eigen::VectorXd &query, double relative=1e-6)
Eigen::MatrixXd forceStopLowestModes(const Eigen::MatrixXd &columns, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, Eigen::Index count, const Eigen::MatrixXd *measured=nullptr)
Eigen::MatrixXd vibrationalComplement(const Eigen::VectorXd &positions, const Eigen::VectorXd &masses)
Eigen::VectorXd movingAtomicMasses(const gpr::AtomsConfiguration &config, Eigen::Index n_moving)
StencilIndex analyzeStencilIndex(const Eigen::MatrixXd &columns, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, const Eigen::MatrixXd *measured=nullptr)
Eigen::MatrixXd stencilDirectionsForMode(VibrationalStencil mode, const Eigen::VectorXd &positions, const Eigen::VectorXd &masses, bool periodic, bool anchored, const Eigen::VectorXi *frozen=nullptr)
bool forceStopStencilCertifies(bool measured, bool first_order) noexcept
ForceStopStencilPlan planForceStopStencil(ForceStopStencilQuery query)
constexpr int forceStopMinModeEscapes() noexcept
Min-mode escapes after a higher-order certificate, for every search.
ForceStopCertificateResult runForceStopCertificate(Measure measure, Refine refine, ForceStopStencilPlan plan, const ForceStopMeasurement *prior=nullptr)
double variance(const Weights &w, const Matrix &covariance)
FieldMatrixd Coord
Definition Macros.h:35
Stores configurations of all atoms in the system.
Definition Structures.h:832
FieldMatrixU8 is_frozen
Indicates whether atom is frozen or not.
Definition Structures.h:834
AtomsPositionAndType atoms_mov
Info on moving atoms.
Definition Structures.h:844
Eigen::VectorXd atomic_masses
Per-atom input masses; empty selects unit masses.
Definition Structures.h:838
Observation data: energy, gradient and positions.
FieldMatrixd E
std::vector< int > measured
1 for a mode at least 99% inside the measured directions.
detail::OwnedImageState observations
Eigen::MatrixXd lowest_modes
Lowest Cartesian modes, lowest curvature first.
Configuration for GP-NEB.
Definition GPNEB.h:246
Eigen::Index oracle_batch_chunk
Definition GPNEB.h:259
bool outer_budget_per_image
Definition GPNEB.h:300
NEBBatchOracle batch_oracle
Definition GPNEB.h:253
bool force_stop_certificate
Definition GPNEB.h:847
gpr::optim::VibrationalStencil vibrational_stencil
Definition GPNEB.h:852
bool saddle_stage_follows
Definition GPNEB.h:863
double ci_stencil_step
Definition GPNEB.h:856
bool index_refused
A force-quiet point failed the index-1 gate and no budget remains.
Definition GPNEB.h:3690
Eigen::MatrixXd force_stop_positions
Definition GPNEB.h:3768
double force_stop_negative_pair_upper
Definition GPNEB.h:3785
bool index_checked
The vibrational-index gate ran on this result.
Definition GPNEB.h:3688
Eigen::MatrixXd force_stop_modes
Lowest Cartesian modes of the measured Hessian, lowest first.
Definition GPNEB.h:3774
Eigen::VectorXd force_stop_energies
Definition GPNEB.h:3772
Eigen::MatrixXd force_stop_refinement_positions
Definition GPNEB.h:3781
double force_stop_negative_upper
Definition GPNEB.h:3783
double returned_true_force
Definition GPNEB.h:3730
bool force_stop_center_reused
Definition GPNEB.h:3776
GPNEBConvergenceStatus convergence_status
Definition GPNEB.h:3685
bool force_stop_refinement_recorded
Definition GPNEB.h:3786
Eigen::MatrixXd force_stop_gradients
Definition GPNEB.h:3771
Eigen::MatrixXd force_stop_refinement_gradients
Definition GPNEB.h:3782
double force_stop_positive_lower
Definition GPNEB.h:3784
bool index_continue
The gate stepped the climbing image; the caller resumes the search.
Definition GPNEB.h:3692
bool force_stop_deferred
The saddle owns the index. This stage did not measure a stencil.
Definition GPNEB.h:3765
bool force_stop_refinement_higher_order
Definition GPNEB.h:3787
double force_stop_wall_s
Definition GPNEB.h:3777
double index_resolution
Definition GPNEB.h:3695
int force_stop_certificate_calls
Definition GPNEB.h:3759
std::unique_ptr< NEBPath > path
Definition GPNEB.h:3682
Eigen::MatrixXd force_stop_directions
Orthonormal Cartesian directions of that stencil, one column each.
Definition GPNEB.h:3770
double force_stop_displacement
Definition GPNEB.h:3775
bool force_stop_inconclusive
The stencil was measured and did not resolve an index.
Definition GPNEB.h:3767
Float64 central-difference index of one geometry.
bool hand_off
A following saddle receives handed.
Eigen::VectorXd center
Stencil geometries (columns) and gradients (rows) already paid for.
bool defer_certificate
Do not measure. The following saddle certifies the point it reaches.
bool columns_already_measured
Finite-difference columns at this geometry were already paid for.