Loading...
Searching...
No Matches
HarmonicPrefactor.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
5#include "HarmonicPrefactor.h"
6
7#include <algorithm>
8#include <cmath>
9#include <limits>
10#include <stdexcept>
11#include <utility>
12
17#include "StencilIndex.h"
18
19namespace gpr::htst {
20namespace {
21
22constexpr double kTwoPi = 6.283185307179586476925286766559;
23
24struct Spectrum {
25 Eigen::VectorXd eigenvalues;
28 Eigen::MatrixXd directions;
29 int n_projected = 0;
31 bool finite = true;
32};
33
36bool normalPositive(double value)
37{
38 return value > 0.0 && std::isnormal(value);
39}
40
41Eigen::VectorXd coordinateMasses(const Eigen::VectorXd& x,
42 const Options& options)
43{
44 const Eigen::Index dof = x.size();
45 if (options.masses.size() == 0) return Eigen::VectorXd::Ones(dof);
46 if (dof % 3 != 0 || options.masses.size() * 3 != dof ||
47 !options.masses.unaryExpr(&normalPositive).all())
48 throw std::invalid_argument(
49 "HTST needs one positive mass per atom of the coordinates, "
50 "each a normal double");
51 Eigen::VectorXd out(dof);
52 for (Eigen::Index k = 0; k < dof; ++k)
53 out(k) = options.masses(k / 3);
54 return out;
55}
56
57void validate(const Eigen::VectorXd& x, const Options& options)
58{
59 if (x.size() == 0 || !x.allFinite())
60 throw std::invalid_argument("HTST needs a finite point");
61 if ((options.project_translation || options.project_rotation) &&
62 x.size() % 3 != 0)
63 throw std::invalid_argument(
64 "rigid-mode projection needs 3N coordinates");
65 if (!normalPositive(options.omega_scale) || !(options.tolerance > 0.0) ||
66 !std::isfinite(options.tolerance) || !(options.fd_step > 0.0) ||
67 !std::isfinite(options.fd_step) || options.max_measured < 0 ||
68 !std::isfinite(options.variance_step))
69 throw std::invalid_argument("invalid HTST option");
70}
71
72Spectrum spectrum(const Eigen::MatrixXd& hessian, const Eigen::VectorXd& x,
73 const Options& options)
74{
75 const Eigen::Index dof = x.size();
76 const Eigen::VectorXd mass = coordinateMasses(x, options);
77 const Eigen::VectorXd inverse_root = mass.cwiseSqrt().cwiseInverse();
78
79 // Rigid motions in mass-weighted coordinates.
80 Eigen::MatrixXd basis = Eigen::MatrixXd::Identity(dof, dof);
81 int projected = 0;
82 if (options.project_translation && options.project_rotation) {
83 const Eigen::Index atoms = dof / 3;
84 Eigen::VectorXd atomic_masses(atoms);
85 for (Eigen::Index a = 0; a < atoms; ++a)
86 atomic_masses(a) = mass(3 * a);
87 basis = optim::vibrationalComplement(x, atomic_masses);
88 projected = static_cast<int>(dof - basis.cols());
89 } else if (options.project_translation || options.project_rotation) {
90 const Eigen::Index atoms = dof / 3;
91 Eigen::VectorXd atomic_masses(atoms);
92 for (Eigen::Index a = 0; a < atoms; ++a)
93 atomic_masses(a) = mass(3 * a);
94 const Eigen::MatrixXd all_rigid =
95 optim::massWeightedRigidMotions(x, atomic_masses);
96 const Eigen::MatrixXd rigid = options.project_translation
97 ? all_rigid.leftCols<3>()
98 : all_rigid.rightCols<3>();
99 const Eigen::JacobiSVD<Eigen::MatrixXd> svd(rigid, Eigen::ComputeFullU);
100 const auto& values = svd.singularValues();
101 const double cut = 1e-10 * std::max(values.size() ? values(0) : 0.0,
102 std::numeric_limits<double>::min());
103 for (Eigen::Index k = 0; k < values.size(); ++k)
104 if (values(k) > cut) ++projected;
105 basis = svd.matrixU().rightCols(dof - projected);
106 }
107 Spectrum out;
108 out.n_projected = projected;
109 if (basis.cols() == 0) return out;
110 const Eigen::MatrixXd weighted = inverse_root.asDiagonal() *
111 (0.5 * (hessian + hessian.transpose())) *
112 inverse_root.asDiagonal();
113 Eigen::MatrixXd block = basis.transpose() * weighted * basis;
114 block = (0.5 * (block + block.transpose())).eval();
115 if (!block.allFinite()) {
116 out.finite = false;
117 out.eigenvalues = Eigen::VectorXd::Constant(
118 block.rows(), std::numeric_limits<double>::quiet_NaN());
119 return out;
120 }
121 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(block);
122 if (solver.info() != Eigen::Success)
123 throw std::runtime_error("HTST eigensolve failed");
124 out.eigenvalues = solver.eigenvalues();
125 out.directions =
126 inverse_root.asDiagonal() * (basis * solver.eigenvectors());
127 return out;
128}
129
130double zeroCutoff(const Spectrum& s, Eigen::Index dof)
131{
132 return 64.0 * std::numeric_limits<double>::epsilon() *
133 static_cast<double>(std::max<Eigen::Index>(1, dof)) *
134 s.eigenvalues.cwiseAbs().maxCoeff();
135}
136
137Half unavailableHalf(Kind kind, Source source, Eigen::Index n_coords,
138 double omega_scale, std::string message)
139{
140 Half half;
142 half.kind = kind;
143 half.source = source;
144 half.n_coords = static_cast<int>(n_coords);
145 half.omega_scale = omega_scale;
146 half.message = std::move(message);
147 return half;
148}
149
152void markUnavailable(Half& half, int calls, Eigen::Index measured_directions,
153 std::string message)
154{
156 half.converged = false;
157 half.oracle_calls = calls;
158 half.n_measured = static_cast<int>(measured_directions);
159 half.message = std::move(message);
160}
161
173Half summarize(const Spectrum& s, const Eigen::VectorXd& x, Kind kind,
174 const Options& options, double ln_sum_std)
175{
176 Half half;
177 half.kind = kind;
178 half.n_coords = static_cast<int>(x.size());
179 half.n_projected = s.n_projected;
180 half.omega_scale = options.omega_scale;
181 const Eigen::Index modes = s.eigenvalues.size();
182 const auto unavailable = [&half](const char* message) {
184 half.message = message;
185 half.frequencies.resize(0);
186 half.n_negative = 0;
187 half.n_modes = 0;
188 half.ln_sum = 0.0;
189 half.ln_sum_std = 0.0;
190 half.imaginary_frequency = 0.0;
191 return half;
192 };
193 if (modes == 0)
194 return unavailable(
195 "no vibrational modes remain after rigid projection");
196 if (!s.finite)
197 return unavailable(
198 "the mass-weighted Hessian overflows the double range");
199 if (!s.eigenvalues.allFinite())
200 return unavailable("Hessian eigenvalues are not finite");
201 const double ln_scale = std::log(options.omega_scale) - std::log(kTwoPi);
202 half.frequencies.resize(modes);
203 const double zero_cut = zeroCutoff(s, x.size());
204 double ln_sum = 0.0;
205 int negative = 0, real = 0;
206 for (Eigen::Index i = 0; i < modes; ++i) {
207 const double value = s.eigenvalues(i);
208 // Exact and scale-aware near-zero eigenvalues are neither sign.
209 // A numerical sign flip must not count as the saddle mode, and a
210 // stored frequency of zero is +0.
211 if (std::abs(value) <= zero_cut) {
212 half.frequencies(i) = 0.0;
213 continue;
214 }
215 if (!std::isnormal(value))
216 return unavailable(
217 "a Hessian eigenvalue is subnormal and has lost its "
218 "significant bits");
219 const double ln_frequency = 0.5 * std::log(std::abs(value)) + ln_scale;
220 const double frequency = std::exp(ln_frequency);
221 if (!std::isfinite(frequency))
222 return unavailable(
223 "a vibrational frequency overflows the double range at this "
224 "omega_scale");
225 if (!std::isnormal(frequency))
226 return unavailable(
227 "a vibrational frequency underflows the normal double range "
228 "at this omega_scale");
229 if (value < 0.0) {
230 half.frequencies(i) = -frequency;
231 ++negative;
232 if (negative == 1 && kind == Kind::Saddle)
233 half.imaginary_frequency = frequency;
234 continue;
235 }
236 half.frequencies(i) = frequency;
237 ln_sum += ln_frequency;
238 ++real;
239 }
240 if (!std::isfinite(ln_sum))
241 return unavailable("ln_sum overflows the double range");
242 if (!std::isfinite(ln_sum_std) || ln_sum_std < 0.0)
243 return unavailable(
244 "the estimated spread of ln_sum is not finite in double "
245 "precision");
246 half.n_negative = negative;
247 half.n_modes = real;
248 half.ln_sum = ln_sum;
249 half.ln_sum_std = ln_sum_std;
250 const int expected = kind == Kind::Saddle ? 1 : 0;
251 half.status = negative == expected && real + negative == modes
252 ? Status::Ok
254 if (kind == Kind::Minimum) half.imaginary_frequency = 0.0;
255 half.measured.assign(static_cast<std::size_t>(modes), 0);
256 return half;
257}
258
259Eigen::VectorXd centralAction(const GradientOracle& oracle,
260 const Eigen::VectorXd& x,
261 const Eigen::VectorXd& direction, double step)
262{
263 const Eigen::VectorXd plus = oracle(x + step * direction);
264 const Eigen::VectorXd minus = oracle(x - step * direction);
265 if (plus.size() != x.size() || minus.size() != x.size() ||
266 !plus.allFinite() || !minus.allFinite())
267 throw std::runtime_error("oracle gradient is not finite");
268 return (plus - minus) / (2.0 * step);
269}
270
271} // namespace
272
279 Eigen::Index dof)
280{
281 Options out = options;
282 const bool anchored = atoms.atoms_froz_active.positions.size() > 0 ||
283 atoms.atoms_froz_inactive.positions.size() > 0 ||
284 (atoms.is_frozen.array() == FROZEN_ATOM).any();
285 if (anchored) {
286 out.project_translation = false;
287 out.project_rotation = false;
288 } else if (gpr::geometry::cellIsMicLattice(atoms.cell)) {
289 out.project_rotation = false;
290 }
291 if (out.masses.size() == 0 && atoms.atomic_masses.size() > 0) {
292 if (dof <= 0 || dof % 3 != 0)
293 throw std::invalid_argument(
294 "HTST needs one positive mass per atom of the coordinates");
295 out.masses = optim::movingAtomicMasses(atoms, dof / 3);
296 }
297 return out;
298}
299
300Half fromHessian(const Eigen::MatrixXd& hessian, const Eigen::VectorXd& x,
301 Kind kind, const Options& options)
302{
303 validate(x, options);
304 (void)coordinateMasses(x, options);
305 if (hessian.rows() != x.size() || hessian.cols() != x.size() ||
306 !hessian.allFinite())
307 throw std::invalid_argument("HTST needs a finite d x d Hessian");
308 Half half = summarize(spectrum(hessian, x, options), x, kind, options, 0.0);
310 if (half.status != Status::Unavailable) {
311 half.converged = true;
312 std::fill(half.measured.begin(), half.measured.end(), 1);
313 half.n_measured = static_cast<int>(half.measured.size());
314 }
315 return half;
316}
317
318Half measured(const GradientOracle& oracle, const Eigen::VectorXd& x, Kind kind,
319 const Options& options)
320{
321 validate(x, options);
322 (void)coordinateMasses(x, options);
323 const Eigen::Index dof = x.size();
324 Eigen::MatrixXd hessian(dof, dof);
325 for (Eigen::Index j = 0; j < dof; ++j)
326 hessian.col(j) = centralAction(oracle, x, Eigen::VectorXd::Unit(dof, j),
327 options.fd_step);
328 Half half = fromHessian(hessian, x, kind, options);
329 half.oracle_calls = static_cast<int>(2 * dof);
330 return half;
331}
332
333Half surrogate(GaussianProcessRegression& gp, const Eigen::VectorXd& x,
334 Kind kind, const Options& options)
335{
336 return refined(gp, GradientOracle{}, x, kind, options);
337}
338
340 const Eigen::VectorXd& x, Kind kind, const Options& raw_options)
341{
342 const Options options =
343 geometryOptions(raw_options, gp.getAtomsConfig(), x.size());
344 validate(x, options);
345 (void)coordinateMasses(x, options);
346 const Eigen::Index dof = x.size();
347 Eigen::MatrixXd fixed_hessian;
348 if (gp.findConditionedHessian(x, fixed_hessian)) {
349 Half half = fromHessian(fixed_hessian, x, kind, options);
351 return half;
352 }
353 std::vector<Eigen::MatrixXd> hessians;
354 const auto report =
355 posterior::meanHessians(gp, x.transpose(), {}, hessians);
356 if (!report.ok()) {
358 throw std::invalid_argument(report.message);
359 return unavailableHalf(kind,
361 dof, options.omega_scale, report.message);
362 }
363 if (hessians.empty())
364 return unavailableHalf(
365 kind, oracle ? Source::Refined : Source::Surrogate, dof,
366 options.omega_scale, "posterior returned no Hessian");
367 const Eigen::MatrixXd surrogate_hessian = hessians[0];
368 posterior::DerivativeOptions variance_options;
369 variance_options.variance_step = options.variance_step;
370
371 Eigen::MatrixXd S(dof, 0), W(dof, 0);
372 Eigen::MatrixXd corrected = surrogate_hessian;
373 int calls = 0;
374 double previous = std::numeric_limits<double>::quiet_NaN();
375 Half half;
376 for (int round = 0;; ++round) {
377 const Spectrum s = spectrum(corrected, x, options);
378 const Eigen::Index modes = s.eigenvalues.size();
379 // No vibrational complement leaves an empty spectrum. summarize
380 // reports that; reducing the empty vector is undefined.
381 if (modes == 0 || !s.finite || !s.eigenvalues.allFinite()) {
382 half = summarize(s, x, kind, options, 0.0);
383 half.n_measured = static_cast<int>(S.cols());
384 half.oracle_calls = calls;
385 half.source = oracle ? Source::Refined : Source::Surrogate;
386 break;
387 }
388 const int budget =
389 options.max_measured > 0
390 ? std::min<int>(options.max_measured, static_cast<int>(modes))
391 : static_cast<int>(modes);
392
393 // Unmeasured part of each mode and the GP spread of its curvature.
394 Eigen::MatrixXd outside = s.directions;
395 if (S.cols() > 0) outside -= S * (S.transpose() * s.directions);
396 Eigen::VectorXd spread = Eigen::VectorXd::Zero(modes);
397 std::vector<int> inside(static_cast<std::size_t>(modes), 0);
398 std::vector<Eigen::Index> open;
399 for (Eigen::Index i = 0; i < modes; ++i) {
400 const double total = s.directions.col(i).squaredNorm();
401 const double out = outside.col(i).squaredNorm();
402 if (out <= 0.01 * total) inside[static_cast<std::size_t>(i)] = 1;
403 if (out > 1e-16 * total) open.push_back(i);
404 }
405 const double zero_cut = zeroCutoff(s, dof);
406 double ln_sum_std = 0.0;
407 if (!open.empty()) {
408 const Eigen::Index count = static_cast<Eigen::Index>(open.size());
409 // Unit query directions keep the variance in range for any mass
410 // scale; var(o^T H o) = norm(o)^4 var(u^T H u) for o = norm(o) u.
411 Eigen::MatrixXd block(count, dof);
412 Eigen::VectorXd norms(count);
413 for (Eigen::Index k = 0; k < count; ++k) {
414 const auto column =
415 outside.col(open[static_cast<std::size_t>(k)]);
416 norms(k) = column.stableNorm();
417 block.row(k) = (column / norms(k)).transpose();
418 }
419 std::vector<Eigen::VectorXd> variance;
421 gp, x.transpose(), {block}, variance_options, variance);
422 if (!status.ok()) {
423 half = summarize(s, x, kind, options, 0.0);
424 half.measured = inside;
425 half.n_measured = static_cast<int>(S.cols());
426 half.oracle_calls = calls;
427 half.source = oracle ? Source::Refined : Source::Surrogate;
429 half.message = status.message;
430 break;
431 }
432 const Eigen::VectorXd& diagonal = variance[0];
433 // sqrt(var_i) / (2 lambda_i) in log space: neither the fourth
434 // power of norm(o) nor 1 / lambda_i^2 is formed.
435 Eigen::VectorXd terms = Eigen::VectorXd::Zero(count);
436 for (Eigen::Index k = 0; k < count; ++k) {
437 const Eigen::Index i = open[static_cast<std::size_t>(k)];
438 const double ln_root = std::log(0.5) +
439 0.5 * std::log(diagonal(k)) +
440 2.0 * std::log(norms(k));
441 spread(i) = std::exp(
442 ln_root -
443 std::log(std::max(std::abs(s.eigenvalues(i)),
444 std::numeric_limits<double>::min())));
445 if (s.eigenvalues(i) > zero_cut)
446 terms(k) = std::exp(ln_root - std::log(s.eigenvalues(i)));
447 }
448 ln_sum_std = terms.stableNorm();
449 }
450 half = summarize(s, x, kind, options, ln_sum_std);
451 half.measured = inside;
452 half.n_measured = static_cast<int>(S.cols());
453 half.oracle_calls = calls;
454 half.source = oracle ? Source::Refined : Source::Surrogate;
455 if (half.status == Status::Unavailable) break;
456
457 double widest = 0.0;
458 Eigen::Index pick = -1;
459 for (const Eigen::Index i: open)
460 if (spread(i) > widest || pick < 0) {
461 widest = spread(i);
462 pick = i;
463 }
464 if (round > 0 && std::abs(half.ln_sum - previous) < options.tolerance &&
465 widest < options.tolerance && half.ln_sum_std < options.tolerance) {
466 half.converged = true;
467 break;
468 }
469 if (!oracle) {
471 half.converged = widest < options.tolerance &&
472 half.ln_sum_std < options.tolerance;
473 break;
474 }
475 if (pick < 0 || S.cols() >= budget || S.cols() >= dof) {
476 // Every vibrational direction measured is the measured Hessian.
477 half.converged = S.cols() >= static_cast<Eigen::Index>(modes);
478 break;
479 }
480 Eigen::VectorXd direction = outside.col(pick);
481 for (int pass = 0; pass < 2 && S.cols() > 0; ++pass)
482 direction -= S * (S.transpose() * direction);
483 direction.normalize();
484 if (!direction.allFinite() ||
485 std::abs(direction.squaredNorm() - 1.0) > 1e-8) {
486 markUnavailable(half, calls, S.cols(),
487 "no independent direction is left to measure");
488 break;
489 }
490 const Eigen::VectorXd action =
491 centralAction(oracle, x, direction, options.fd_step);
492 calls += 2;
493 S.conservativeResize(Eigen::NoChange, S.cols() + 1);
494 W.conservativeResize(Eigen::NoChange, W.cols() + 1);
495 S.col(S.cols() - 1) = direction;
496 W.col(W.cols() - 1) = action;
497
498 // Exact on span(S), the surrogate on its complement. An empty
499 // result means the measured actions were not finite or S lost
500 // orthonormality; the spectrum of a 0 x 0 matrix is not a half.
501 corrected = optim::completeMeasuredHessian(surrogate_hessian, S, W);
502 if (corrected.rows() != dof || corrected.cols() != dof) {
503 markUnavailable(half, calls, S.cols(),
504 "measured Hessian actions are not finite or the "
505 "measured directions lost orthonormality");
506 break;
507 }
508 previous = half.ln_sum;
509 }
510 if (half.status == Status::Ok && !half.converged && oracle)
512 return half;
513}
514
516{
517 thread_local SearchRequest request;
518 return request;
519}
520
522{
523 SearchRequest& current = searchRequest();
524 SearchRequest out = current;
525 current.options.masses.resize(0);
526 return out;
527}
528
530 const AtomsConfiguration& atoms, Eigen::Index dof)
531{
532 if (!request.enabled) return;
533 if (dof <= 0 || dof % 3 != 0) {
535 throw std::invalid_argument(
536 "prefactor requests need coordinates for a whole number of atoms");
537 }
538 Options effective;
539 try {
540 effective = geometryOptions(request.options, atoms, dof);
541 } catch (...) {
543 throw;
544 }
545 if (!normalPositive(effective.omega_scale) ||
546 !(effective.tolerance > 0.0) || !std::isfinite(effective.tolerance) ||
547 !(effective.fd_step > 0.0) || !std::isfinite(effective.fd_step) ||
548 effective.max_measured < 0 || !std::isfinite(effective.variance_step)) {
550 throw std::invalid_argument("invalid HTST option");
551 }
552 if (effective.masses.size() > 0) {
553 if (dof <= 0 || dof % 3 != 0 || effective.masses.size() * 3 != dof ||
554 !effective.masses.unaryExpr(&normalPositive).all()) {
556 throw std::invalid_argument(
557 "HTST needs one positive mass per atom of the coordinates, "
558 "each a normal double");
559 }
560 }
561}
562
564{
565 thread_local SearchHalves halves;
566 return halves;
567}
568
569void EvaluationRecord::add(const Eigen::VectorXd& position, double energy,
570 const Eigen::VectorXd& gradient)
571{
572 std::lock_guard<std::mutex> lock(mutex_);
573 positions_.push_back(position);
574 energies_.push_back(energy);
575 gradients_.push_back(gradient);
576}
577
579 std::size_t rows) const
580{
581 std::lock_guard<std::mutex> lock(mutex_);
582 std::vector<std::size_t> order;
583 std::vector<double> distance(positions_.size(), 0.0);
584 for (std::size_t i = 0; i < positions_.size(); ++i) {
585 if (positions_[i].size() != x.size()) continue;
586 order.push_back(i);
587 distance[i] = (positions_[i] - x).squaredNorm();
588 }
589 std::stable_sort(order.begin(), order.end(),
590 [&](std::size_t a, std::size_t b) {
591 return distance[a] < distance[b];
592 });
593 if (order.size() > rows) order.resize(rows);
594 Observation obs;
595 const auto n = static_cast<Eigen::Index>(order.size());
596 obs.R.resize(n, x.size());
597 obs.E.resize(n, 1);
598 obs.G.resize(n, x.size());
599 for (Eigen::Index k = 0; k < n; ++k) {
600 const std::size_t row = order[static_cast<std::size_t>(k)];
601 obs.R.row(k) = positions_[row].transpose();
602 obs.E(k, 0) = energies_[row];
603 obs.G.row(k) = gradients_[row].transpose();
604 }
605 return obs;
606}
607
608namespace {
609
610constexpr std::size_t kSearchHalfRows = 40;
611
612} // namespace
613
614Half searchHalf(const EvaluationRecord& record, const Eigen::VectorXd& x,
615 Kind kind, const InputParameters& params,
616 const AtomsConfiguration& atoms, const GradientOracle& oracle,
617 const SearchRequest& request,
618 const Eigen::MatrixXd* stencil_hessian)
619{
620 const Source requested_source =
621 stencil_hessian
623 : (request.mode == Mode::Measured
625 : (request.mode == Mode::Refined ? Source::Refined
627 const double scale = request.options.omega_scale;
628 try {
629 const Options options =
630 geometryOptions(request.options, atoms, x.size());
631 validate(x, options);
632 (void)coordinateMasses(x, options);
633 if (stencil_hessian) {
634 Half half = fromHessian(*stencil_hessian, x, kind, options);
635 half.source = Source::Stencil;
636 return half;
637 }
638 if (request.mode == Mode::Measured) {
639 if (!oracle)
640 return unavailableHalf(kind, requested_source, x.size(), scale,
641 "measured prefactor requires an oracle");
642 return measured(oracle, x, kind, options);
643 }
644 const Observation obs = record.nearest(x, kSearchHalfRows);
645 if (obs.R.rows() == 0)
646 return unavailableHalf(kind, requested_source, x.size(), scale,
647 "no evaluations near stationary point");
649 gp.initialize(params, atoms);
650 gp.setUseZBLPriorMean(false);
651 gp.setUseFFPriorMean(false);
652 gp.setHyperparameters(obs, atoms);
653 gp.optimize(obs);
654 if (!gp.isDecomposedSuccessfully())
655 return unavailableHalf(kind, requested_source, x.size(), scale,
656 "GP Cholesky decomposition failed");
657 return request.mode == Mode::Refined
658 ? refined(gp, oracle, x, kind, options)
659 : surrogate(gp, x, kind, options);
660 } catch (const std::bad_alloc&) {
661 return unavailableHalf(kind, requested_source, x.size(), scale,
662 "prefactor allocation failed");
663 } catch (const std::exception& error) {
664 return unavailableHalf(kind, requested_source, x.size(), scale,
665 error.what());
666 } catch (...) {
667 return unavailableHalf(kind, requested_source, x.size(), scale,
668 "prefactor computation failed");
669 }
670}
671
673{
674 InputParameters params;
675 params.gp_sigma2.value = 1e-4;
676 params.jitter_sigma2.value = 1e-4;
677 params.sigma2.value = 1e-4;
678 params.magnSigma2.value = 0.0;
679 params.constSigma2.value = 0.0;
680 params.prior_mu.value = 0.0;
681 params.prior_nu.value = 20.0;
682 params.prior_s2.value = 1.0;
683 params.max_iter.value = 400;
684 params.tolerance_func.value = 1e-3;
685 params.tolerance_sol.value = 1e-3;
686 params.report_level.value = 0;
687 params.optimization_alg.value = "SCG_opt";
688 return params;
689}
690
691Half minimumHalf(const EvaluationRecord& record, const Eigen::VectorXd& x,
692 const AtomsConfiguration& atoms, const GradientOracle& oracle,
693 const SearchRequest& request)
694{
695 return searchHalf(record, x, Kind::Minimum, searchParameters(), atoms,
696 oracle, request);
697}
698
699Eigen::MatrixXd stencilHessian(const Eigen::MatrixXd& positions,
700 const Eigen::MatrixXd& gradients, double step)
701{
702 const Eigen::Index dof = positions.rows();
703 if (dof == 0 || positions.cols() != 2 * dof + 1 || !std::isfinite(step) ||
704 !(step > 0.0) || !positions.allFinite() || !gradients.allFinite())
705 return {};
706 const bool by_column =
707 gradients.rows() == dof && gradients.cols() == 2 * dof + 1;
708 const bool by_row =
709 gradients.rows() == 2 * dof + 1 && gradients.cols() == dof;
710 if (!by_column && !by_row) return {};
711 const Eigen::VectorXd center = positions.col(0);
712 const double tol = std::max(
713 1e-9 * step, 64.0 * std::numeric_limits<double>::epsilon() *
714 std::max(1.0, center.cwiseAbs().maxCoeff() + step));
715 for (Eigen::Index j = 0; j < dof; ++j) {
716 Eigen::VectorXd expected_plus = center;
717 expected_plus(j) += step;
718 Eigen::VectorXd expected_minus = center;
719 expected_minus(j) -= step;
720 if ((positions.col(2 * j + 1) - expected_plus)
721 .lpNorm<Eigen::Infinity>() > tol ||
722 (positions.col(2 * j + 2) - expected_minus)
723 .lpNorm<Eigen::Infinity>() > tol)
724 return {};
725 }
726 const auto gradient = [&](Eigen::Index k) -> Eigen::VectorXd {
727 return by_column ? Eigen::VectorXd(gradients.col(k))
728 : Eigen::VectorXd(gradients.row(k).transpose());
729 };
730 Eigen::MatrixXd hessian(dof, dof);
731 for (Eigen::Index j = 0; j < dof; ++j)
732 hessian.col(j) =
733 (gradient(2 * j + 1) - gradient(2 * j + 2)) / (2.0 * step);
734 return hessian;
735}
736
738 const EvaluationRecord& record, const Eigen::VectorXd& initial,
739 const Eigen::VectorXd& final_state, const Eigen::VectorXd& climbing,
740 const Eigen::MatrixXd& stencil_positions,
741 const Eigen::MatrixXd& stencil_gradients, double stencil_step,
742 const InputParameters& params, const AtomsConfiguration& atoms,
743 const GradientOracle& oracle, const SearchRequest& request)
744{
745 SearchHalves halves;
746 halves[0] = searchHalf(record, initial, Kind::Minimum, params, atoms,
747 oracle, request);
748 const Eigen::MatrixXd stencil =
749 stencil_positions.rows() == initial.size()
750 ? stencilHessian(stencil_positions, stencil_gradients, stencil_step)
751 : Eigen::MatrixXd();
752 if (stencil.size() > 0)
753 halves[1] = searchHalf(record, stencil_positions.col(0), Kind::Saddle,
754 params, atoms, oracle, request, &stencil);
755 else if (climbing.size() == initial.size())
756 halves[1] = searchHalf(record, climbing, Kind::Saddle, params, atoms,
757 oracle, request);
758 halves[2] = searchHalf(record, final_state, Kind::Minimum, params, atoms,
759 oracle, request);
760 return halves;
761}
762
763} // namespace gpr::htst
@ x
Definition Enums.h:28
@ FROZEN_ATOM
Definition Enums.h:36
void optimize(const Observation &observation)
Optimize paramaters of a Gaussian process.
Definition Optimize.cpp:550
void initialize(const InputParameters &parameters, const AtomsConfiguration &conf_info)
Initialize GPR class.
void setHyperparameters(const Observation &all_obs, const AtomsConfiguration &conf_info, const bool update_sexpat_cf_param=true, const bool update_const_cf_param=true, const bool update_sqrt_prior_param=true)
Set up hyperparameters for GPR.
bool findConditionedHessian(const Eigen::VectorXd &point, Eigen::MatrixXd &hessian_out) const
const AtomsConfiguration & getAtomsConfig() const
Observation nearest(const Eigen::VectorXd &x, std::size_t rows) const
Up to rows evaluations nearest x, nearest first.
void add(const Eigen::VectorXd &position, double energy, const Eigen::VectorXd &gradient)
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
int status
bool cellIsMicLattice(const double cell[9]) noexcept
Nonzero ASE 3x3 that is not the 25 A vacuum convention.
Definition MinImage.h:56
Half surrogate(GaussianProcessRegression &gp, const Eigen::VectorXd &x, Kind kind, const Options &options)
SearchRequest & searchRequest()
This thread's request; it persists until it is assigned again.
InputParameters searchParameters()
Half measured(const GradientOracle &oracle, const Eigen::VectorXd &x, Kind kind, const Options &options)
Full central difference of the oracle gradient: 2 d calls.
void validateSearchRequest(const SearchRequest &request, const AtomsConfiguration &atoms, Eigen::Index dof)
std::function< Eigen::VectorXd(const Eigen::VectorXd &position)> GradientOracle
Half refined(GaussianProcessRegression &gp, const GradientOracle &oracle, const Eigen::VectorXd &x, Kind kind, const Options &raw_options)
Eigen::MatrixXd stencilHessian(const Eigen::MatrixXd &positions, const Eigen::MatrixXd &gradients, double step)
SearchHalves & lastSearchHalves()
The halves of the last search on this thread.
Half fromHessian(const Eigen::MatrixXd &hessian, const Eigen::VectorXd &x, Kind kind, const Options &options)
The half of an exact Hessian in the units of its coordinates.
std::array< std::optional< Half >, 3 > SearchHalves
Half searchHalf(const EvaluationRecord &record, const Eigen::VectorXd &x, Kind kind, const InputParameters &params, const AtomsConfiguration &atoms, const GradientOracle &oracle, const SearchRequest &request, const Eigen::MatrixXd *stencil_hessian)
Half minimumHalf(const EvaluationRecord &record, const Eigen::VectorXd &x, const AtomsConfiguration &atoms, const GradientOracle &oracle, const SearchRequest &request)
The minimizer's half at its result x: searchHalf with searchParameters().
SearchRequest takeSearchRequest()
Options geometryOptions(const Options &options, const AtomsConfiguration &atoms, Eigen::Index dof)
SearchHalves bandHalves(const EvaluationRecord &record, const Eigen::VectorXd &initial, const Eigen::VectorXd &final_state, const Eigen::VectorXd &climbing, const Eigen::MatrixXd &stencil_positions, const Eigen::MatrixXd &stencil_gradients, double stencil_step, const InputParameters &params, const AtomsConfiguration &atoms, const GradientOracle &oracle, const SearchRequest &request)
Eigen::MatrixXd completeMeasuredHessian(const Eigen::MatrixXd &prior, const Eigen::MatrixXd &basis, const Eigen::MatrixXd &action)
Eigen::MatrixXd vibrationalComplement(const Eigen::VectorXd &positions, const Eigen::VectorXd &masses)
Eigen::VectorXd movingAtomicMasses(const gpr::AtomsConfiguration &config, Eigen::Index n_moving)
Eigen::MatrixXd massWeightedRigidMotions(const Eigen::VectorXd &positions, const Eigen::VectorXd &masses)
DerivativeReport hessianBilinearVariances(GaussianProcessRegression &gp, const Eigen::MatrixXd &points, const std::vector< Eigen::MatrixXd > &directions, const DerivativeOptions &options, std::vector< Eigen::VectorXd > &variances)
Diagonal posterior variances of v_i^T H v_i at each point. Computes one stencil functional at a time,...
DerivativeReport meanHessians(GaussianProcessRegression &gp, const Eigen::MatrixXd &points, const DerivativeOptions &options, std::vector< Eigen::MatrixXd > &hessians, Eigen::MatrixXd *residuals)
Full posterior-mean Hessians at the rows of points, symmetrized. residuals, when given,...
Stores configurations of all atoms in the system.
Definition Structures.h:832
AtomsPositionAndType atoms_froz_inactive
Info on inactive frozen atoms.
Definition Structures.h:843
FieldMatrixU8 is_frozen
Indicates whether atom is frozen or not.
Definition Structures.h:834
AtomsPositionAndType atoms_froz_active
Info on active frozen atoms.
Definition Structures.h:841
Eigen::VectorXd atomic_masses
Per-atom input masses; empty selects unit masses.
Definition Structures.h:838
Structure of the input parameters. All input parameters are pairs of string names and values.
Definition Structures.h:370
KeyValuePair< double > prior_s2
Definition Structures.h:650
KeyValuePair< int > max_iter
Definition Structures.h:674
KeyValuePair< std::string > optimization_alg
Definition Structures.h:614
KeyValuePair< double > prior_nu
Definition Structures.h:649
KeyValuePair< int > report_level
Definition Structures.h:673
KeyValuePair< double > jitter_sigma2
Definition Structures.h:613
KeyValuePair< double > constSigma2
Definition Structures.h:618
KeyValuePair< double > tolerance_func
Definition Structures.h:675
KeyValuePair< double > tolerance_sol
Definition Structures.h:676
KeyValuePair< double > prior_mu
Definition Structures.h:648
KeyValuePair< double > sigma2
Definition Structures.h:616
KeyValuePair< double > magnSigma2
Definition Structures.h:617
KeyValuePair< double > gp_sigma2
Definition Structures.h:612
Observation data: energy, gradient and positions.
FieldMatrixd E
Eigen::VectorXd frequencies
std::vector< int > measured
1 for a mode at least 99% inside the measured directions.
double omega_scale
Options::omega_scale of ln_sum and the frequencies.
std::string message
Reason when status is Status::Unavailable, or empty.
double imaginary_frequency
abs(nu) of the unstable saddle mode; zero for a minimum.
double variance_step
Stencil step of the GP curvature variance (0: the primitive default).
double fd_step
Central-difference step of each oracle Hessian action.
int max_measured
Oracle-measured directions at most; 0 allows every vibrational mode.
Eigen::VectorXd masses
Options for batched posterior derivative primitives.