Loading...
Searching...
No Matches
PosteriorDerivatives.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 <algorithm>
8#include <cmath>
9#include <limits>
10#include <stdexcept>
11#include <utility>
12
16
17namespace gpr::posterior {
18namespace {
19
20DerivativeReport refuse(DerivativeStatus status, std::string message)
21{
22 DerivativeReport report;
23 report.status = status;
24 report.message = std::move(message);
25 return report;
26}
27
28std::string negativeMessage(const char* what, double value, int point)
29{
30 return std::string(what) + " " + std::to_string(value) + " at point " +
31 std::to_string(point) +
32 " is negative beyond round-off of its prior scale";
33}
34
38Eigen::VectorXd priorMarginals(GaussianProcessRegression& gp,
39 const Eigen::MatrixXd& positions)
40{
41 const Eigen::Index n = positions.rows();
42 const Eigen::Index channels = positions.cols() + 1;
43 Eigen::VectorXd out(n * channels);
44 const double scale = gp.outputScale();
45 const double scale2 = scale * scale;
47 for (Eigen::Index p = 0; p < n; ++p) {
48 const Coord row = positions.row(p);
49 EigenMatrix rows;
50 Eigen::VectorXd indices;
51 aux_func.assembleMatrixOfRepetitiveCoordinates(row, rows, indices);
52 EigenMatrix prior;
53 gp.evaluateCovarianceMatrix(rows, rows, indices, indices, prior,
54 /*serial_per_rank=*/true);
55 for (Eigen::Index c = 0; c < channels; ++c)
56 out(c * n + p) = prior(c, c) * scale2;
57 }
58 return out;
59}
60
61bool knownUnits(const DerivativeOptions& options)
62{
63 const int energy = static_cast<int>(options.energy_unit);
64 const int length = static_cast<int>(options.length_unit);
65 return energy >= 0 && energy <= 4 && length >= 0 && length <= 3;
66}
67
68double varianceStep(const DerivativeOptions& options)
69{
70 return options.variance_step > 0.0 ? options.variance_step
72}
73
77 const Eigen::MatrixXd& points,
78 const DerivativeOptions& options)
79{
80 if (!knownUnits(options))
81 return refuse(DerivativeStatus::InvalidArgument, "unknown unit tag");
82 if (!std::isfinite(options.max_energy_std) ||
83 !std::isfinite(options.variance_step))
85 "non-finite option value");
86 if (!gp.isDecomposedSuccessfully() || gp.fittedObservations().R.rows() == 0)
87 return refuse(DerivativeStatus::NotTrained, "model not trained");
88 const Eigen::Index dof = gp.fittedObservations().R.cols();
89 if (points.rows() == 0 || points.cols() != dof || !points.allFinite())
91 "points must be finite rows of the training dimension");
92 if (options.project_rigid && dof % 3 != 0)
94 "rigid projection needs 3N coordinates");
95 DerivativeReport report;
96 report.energy_unit = options.energy_unit;
97 report.length_unit = options.length_unit;
98 report.n_points = static_cast<int>(points.rows());
99 report.projected = options.project_rigid;
100 for (Eigen::Index b = 0; b < points.rows(); ++b) {
101 Observation query;
102 query.R = points.row(b);
104 if (query.E.size() < 1 || !std::isfinite(query.E(0, 0)))
105 return refuse(DerivativeStatus::Unsupported,
106 "posterior energy variance is not finite");
107 const double raw = query.E(0, 0);
108 const auto variance =
109 raw < 0.0
110 ? roundoffVariance(raw, priorMarginals(gp, points.row(b))(0))
111 : std::optional<double>(raw);
112 if (!variance)
113 return refuse(DerivativeStatus::Unsupported,
114 negativeMessage("posterior energy variance", raw,
115 static_cast<int>(b)));
116 const double std_dev = std::sqrt(*variance);
117 if (report.max_energy_std_point < 0 ||
118 std_dev > report.max_energy_std) {
119 report.max_energy_std = std_dev;
120 report.max_energy_std_point = static_cast<int>(b);
121 }
122 }
123 if (options.max_energy_std > 0.0 &&
124 report.max_energy_std > options.max_energy_std) {
126 report.message = "posterior energy standard deviation " +
127 std::to_string(report.max_energy_std) + " at point " +
128 std::to_string(report.max_energy_std_point) +
129 " exceeds max_energy_std " +
130 std::to_string(options.max_energy_std);
131 }
132 return report;
133}
134
137 const Eigen::MatrixXd& directions, Eigen::MatrixXd& out)
138{
139 out.resize(directions.rows(), directions.cols());
140 Eigen::VectorXd product;
141 for (Eigen::Index j = 0; j < directions.cols(); ++j) {
142 if (!action(directions.col(j), product) ||
143 product.size() != directions.rows() || !product.allFinite())
144 return false;
145 out.col(j) = product;
146 }
147 return true;
148}
149
151 GaussianProcessRegression& gp, const Eigen::MatrixXd& points,
152 Eigen::Index b)
153{
154 Coord R = points.row(b);
155 return gp.prepareAnalyticMeanHessian(R);
156}
157
158constexpr Eigen::Index kMaxStencilJointDim = 32768;
159
162double representable(long double value, const char* what)
163{
164 const double out = static_cast<double>(value);
165 if (!std::isfinite(out))
166 throw std::range_error(std::string(what) +
167 " is not finite in double precision");
168 if (value != 0.0L && std::abs(out) < std::numeric_limits<double>::min())
169 throw std::range_error(std::string(what) +
170 " underflows the normal double range");
171 return out;
172}
173
174using LongMatrix = Eigen::Matrix<long double, Eigen::Dynamic, Eigen::Dynamic>;
175
178struct Stencil {
179 EigenMatrix positions;
180 LongMatrix weights;
181};
182
184Stencil stencilFunctionals(const Eigen::VectorXd& x,
185 const Eigen::MatrixXd& left,
186 const Eigen::MatrixXd& right, double step)
187{
188 const Eigen::Index dof = x.size();
189 const Eigen::Index kl = left.rows();
190 const Eigen::Index kr = right.rows();
191 const Eigen::Index n = 2 * kr;
192 if (n > kMaxStencilJointDim / (dof + 1))
193 throw std::length_error(
194 "Hessian stencil covariance dimension exceeds memory guard");
195 EigenMatrix positions(n, dof);
196 Eigen::VectorXd norms(kr);
197 Eigen::VectorXd signs = Eigen::VectorXd::Ones(kr);
198 for (Eigen::Index j = 0; j < kr; ++j) {
199 const Eigen::Matrix<long double, 1, Eigen::Dynamic> row =
200 right.row(j).cast<long double>();
201 const long double norm = row.norm();
202 norms(j) = static_cast<double>(norm);
203 Eigen::RowVectorXd unit = Eigen::RowVectorXd::Zero(dof);
204 if (norm > 0.0L) {
205 Eigen::Index pivot = 0;
206 row.cwiseAbs().maxCoeff(&pivot);
207 if (row(pivot) < 0.0L) signs(j) = -1.0;
208 unit = (static_cast<long double>(signs(j)) * (row / norm))
209 .cast<double>();
210 }
211 positions.row(2 * j) = x.transpose() + step * unit;
212 positions.row(2 * j + 1) = x.transpose() - step * unit;
213 }
214 // Channel order: every energy, then gradient column c of every point.
215 // Formed in long double: norm(v) * norm(w) can leave the double range even
216 // when the covariance itself does not.
217 LongMatrix w = LongMatrix::Zero(kl * kr, n * (dof + 1));
218 for (Eigen::Index i = 0; i < kl; ++i)
219 for (Eigen::Index j = 0; j < kr; ++j) {
220 const long double scale = static_cast<long double>(signs(j)) *
221 static_cast<long double>(norms(j)) /
222 (2.0L * step);
223 for (Eigen::Index c = 0; c < dof; ++c) {
224 const Eigen::Index base = n + c * n;
225 const long double term =
226 scale * static_cast<long double>(left(i, c));
227 w(i * kr + j, base + 2 * j) += term;
228 w(i * kr + j, base + 2 * j + 1) -= term;
229 }
230 }
231 return {std::move(positions), std::move(w)};
232}
233
236Eigen::Matrix<long double, Eigen::Dynamic, 1> stencilPriorRoots(
237 GaussianProcessRegression& gp, const Stencil& stencil)
238{
239 const Eigen::VectorXd marginals = priorMarginals(gp, stencil.positions);
240 Eigen::Matrix<long double, Eigen::Dynamic, 1> roots(marginals.size());
241 for (Eigen::Index c = 0; c < marginals.size(); ++c)
242 roots(c) =
243 std::sqrt(static_cast<long double>(std::max(marginals(c), 0.0)));
244 return stencil.weights.cwiseAbs() * roots;
245}
246
247double stencilPriorScale(GaussianProcessRegression& gp, const Stencil& stencil,
248 Eigen::Index r)
249{
250 const long double root = stencilPriorRoots(gp, stencil)(r);
251 return static_cast<double>(root * root);
252}
253
254Eigen::MatrixXd stencilCovariance(GaussianProcessRegression& gp,
255 const Stencil& stencil)
256{
257 const Eigen::Index joint_dim = stencil.weights.cols();
258 EigenMatrix joint;
259 gp.calculateObservationPosteriorCovariance(stencil.positions, joint);
260 if (joint.rows() != joint_dim || joint.cols() != joint_dim)
261 throw std::runtime_error("posterior covariance has the wrong shape");
262 const LongMatrix& w = stencil.weights;
263 // w J w^T. A blocked product folds sibling rows into one panel. Scalar
264 // Eigen's summation order replaces packet order, so that panel sum
265 // depends on how many rows share it and a one-row stencil no longer
266 // matches the same row inside a taller product. One matrix-vector
267 // product per row has a single summation tree: the entry follows that
268 // row alone, and negating the row negates the entry.
269 const LongMatrix joint_ld = joint.cast<long double>();
270 const Eigen::Index rows = w.rows();
271 LongMatrix product(rows, rows);
272 for (Eigen::Index col = 0; col < rows; ++col) {
273 const Eigen::Matrix<long double, Eigen::Dynamic, 1> weighted =
274 joint_ld * w.row(col).transpose();
275 for (Eigen::Index row = 0; row < rows; ++row)
276 product(row, col) = w.row(row).dot(weighted);
277 }
278 Eigen::MatrixXd covariance(product.rows(), product.cols());
279 for (Eigen::Index i = 0; i < product.rows(); ++i)
280 for (Eigen::Index j = 0; j < product.cols(); ++j)
281 covariance(i, j) =
282 representable(product(i, j), "Hessian stencil covariance");
283 return 0.5 * (covariance + covariance.transpose());
284}
285
288class TrainingRollback {
289public:
290 TrainingRollback(GaussianProcessRegression& gp, const Observation& training)
291 : gp_(gp), training_(training)
292 {
293 }
294 TrainingRollback(const TrainingRollback&) = delete;
295 TrainingRollback& operator=(const TrainingRollback&) = delete;
296 ~TrainingRollback()
297 {
298 if (!armed_) return;
299 try {
300 gp_.updateModelWithFullData(training_);
301 } catch (...) {
302 }
303 }
304 void release() noexcept
305 {
306 armed_ = false;
307 }
308
309private:
311 const Observation& training_;
312 bool armed_ = true;
313};
314
315} // namespace
316
317std::optional<double> roundoffVariance(double variance,
318 double prior_scale) noexcept
319{
320 if (!std::isfinite(variance)) return std::nullopt;
321 if (variance >= 0.0) return variance;
322 if (std::isfinite(prior_scale) && prior_scale > 0.0 &&
323 -variance <= kNegativeVarianceTolerance * prior_scale)
324 return 0.0;
325 return std::nullopt;
326}
327
328Eigen::MatrixXd rigidGenerators(const Eigen::VectorXd& positions)
329{
330 const Eigen::Index dof = positions.size();
331 if (dof == 0 || dof % 3 != 0) return Eigen::MatrixXd::Zero(dof, 6);
332 const Eigen::Index atoms = dof / 3;
333 Eigen::MatrixXd generators = optim::massWeightedRigidMotions(
334 positions, Eigen::VectorXd::Ones(atoms));
335 generators.rightCols<3>() = -generators.rightCols<3>();
336 const double tiny = 64.0 * std::numeric_limits<double>::epsilon() *
337 std::max(generators.rightCols<3>().norm(), 1.0) *
338 std::sqrt(static_cast<double>(atoms));
339 for (Eigen::Index k = 0; k < 6; ++k) {
340 const double norm = generators.col(k).norm();
341 if (norm > tiny)
342 generators.col(k) /= norm;
343 else
344 generators.col(k).setZero();
345 }
346 return generators;
347}
348
349Eigen::MatrixXd rigidProjector(const Eigen::VectorXd& positions,
350 const AtomsConfiguration& config)
351{
352 const Eigen::Index dof = positions.size();
353 if (dof == 0 || dof % 3 != 0) return Eigen::MatrixXd::Identity(dof, dof);
354 Coord coord(1, dof);
355 coord.row(0) = positions.transpose();
356 const Eigen::MatrixXd basis =
357 optim::physicalCurvatureBasis(coord, config, /*exclude_rotations=*/true,
359 if (basis.cols() == 0) return Eigen::MatrixXd::Zero(dof, dof);
360 if (basis.cols() == dof) return Eigen::MatrixXd::Identity(dof, dof);
361 return basis * basis.transpose();
362}
363
364Eigen::MatrixXd rigidProjector(const Eigen::VectorXd& positions)
365{
366 return rigidProjector(positions, AtomsConfiguration{});
367}
368
370 const Eigen::MatrixXd& points,
371 const DerivativeOptions& options,
372 std::vector<Eigen::MatrixXd>& hessians,
373 Eigen::MatrixXd* residuals)
374{
375 DerivativeReport report = admit(gp, points, options);
376 if (!report.ok()) return report;
377 if (residuals != nullptr && points.cols() % 3 != 0)
379 "rigid residuals need 3N coordinates");
380 const Eigen::Index dof = points.cols();
381 std::vector<Eigen::MatrixXd> out(static_cast<std::size_t>(points.rows()));
382 Eigen::MatrixXd residual_rows;
383 if (residuals != nullptr) residual_rows.resize(points.rows(), 6);
384 const Eigen::MatrixXd identity = Eigen::MatrixXd::Identity(dof, dof);
385 for (Eigen::Index b = 0; b < points.rows(); ++b) {
386 auto action = prepare(gp, points, b);
387 Eigen::MatrixXd columns;
388 if (!action || !applyAt(action, identity, columns))
389 return refuse(DerivativeStatus::Unsupported,
390 "no analytic mean Hessian for this model");
391 Eigen::MatrixXd hessian = 0.5 * (columns + columns.transpose());
392 if (residuals != nullptr) {
393 const Eigen::MatrixXd generators =
394 rigidGenerators(points.row(b).transpose());
395 for (Eigen::Index k = 0; k < 6; ++k) {
396 const double value = generators.col(k).squaredNorm() > 0.0
397 ? (hessian * generators.col(k)).norm()
398 : -1.0;
399 residual_rows(b, k) = value;
400 double& peak = k < 3 ? report.max_translation_residual
401 : report.max_rotation_residual;
402 peak = std::max(peak, value);
403 }
404 }
405 if (options.project_rigid) {
406 const Eigen::MatrixXd P =
407 rigidProjector(points.row(b).transpose(), gp.getAtomsConfig());
408 hessian = P * hessian * P;
409 hessian = 0.5 * (hessian + hessian.transpose()).eval();
410 }
411 out[static_cast<std::size_t>(b)] = std::move(hessian);
412 }
413 hessians = std::move(out);
414 if (residuals != nullptr) *residuals = std::move(residual_rows);
415 return report;
416}
417
419 GaussianProcessRegression& gp, const Eigen::MatrixXd& points,
420 const std::vector<Eigen::MatrixXd>& directions,
421 const DerivativeOptions& options, std::vector<Eigen::MatrixXd>& actions)
422{
423 if (directions.size() != static_cast<std::size_t>(points.rows()))
425 "one direction block per point");
426 for (const auto& block: directions)
427 if (block.rows() == 0 || block.cols() != points.cols() ||
428 !block.allFinite())
430 "direction blocks must be finite k x d");
431 DerivativeReport report = admit(gp, points, options);
432 if (!report.ok()) return report;
433 std::vector<Eigen::MatrixXd> out(directions.size());
434 for (Eigen::Index b = 0; b < points.rows(); ++b) {
435 auto action = prepare(gp, points, b);
436 Eigen::MatrixXd vectors =
437 directions[static_cast<std::size_t>(b)].transpose();
438 Eigen::MatrixXd P;
439 if (options.project_rigid) {
440 P = rigidProjector(points.row(b).transpose(), gp.getAtomsConfig());
441 vectors = (P * vectors).eval();
442 }
443 Eigen::MatrixXd products;
444 if (!action || !applyAt(action, vectors, products))
445 return refuse(DerivativeStatus::Unsupported,
446 "no analytic mean Hessian for this model");
447 if (options.project_rigid) products = (P * products).eval();
448 out[static_cast<std::size_t>(b)] = products.transpose();
449 }
450 actions = std::move(out);
451 return report;
452}
453
455 GaussianProcessRegression& gp, const Eigen::MatrixXd& points,
456 const std::vector<Eigen::MatrixXd>& left,
457 const std::vector<Eigen::MatrixXd>& right, const DerivativeOptions& options,
458 std::vector<Eigen::MatrixXd>& covariance)
459{
460 const std::size_t count = static_cast<std::size_t>(points.rows());
461 if (left.size() != count || right.size() != count)
463 "one left and one right block per point");
464 for (std::size_t b = 0; b < count; ++b)
465 if (left[b].rows() == 0 || right[b].rows() == 0 ||
466 left[b].cols() != points.cols() ||
467 right[b].cols() != points.cols() || !left[b].allFinite() ||
468 !right[b].allFinite())
470 "vector blocks must be finite k x d");
471 DerivativeReport report = admit(gp, points, options);
472 if (!report.ok()) return report;
473 const double step = varianceStep(options);
474 std::vector<Eigen::MatrixXd> out(count);
475 for (std::size_t b = 0; b < count; ++b) {
476 const Eigen::VectorXd x = points.row(static_cast<Eigen::Index>(b));
477 Eigen::MatrixXd v = left[b];
478 Eigen::MatrixXd w = right[b];
479 if (options.project_rigid) {
480 const Eigen::MatrixXd P = rigidProjector(x, gp.getAtomsConfig());
481 v = (v * P).eval();
482 w = (w * P).eval();
483 }
484 try {
485 const Stencil stencil = stencilFunctionals(x, v, w, step);
486 Eigen::MatrixXd covariance = stencilCovariance(gp, stencil);
487 for (Eigen::Index r = 0; r < covariance.rows(); ++r) {
488 const double raw = covariance(r, r);
489 if (!(raw < 0.0)) continue;
490 const auto variance =
491 roundoffVariance(raw, stencilPriorScale(gp, stencil, r));
492 if (!variance)
493 return refuse(DerivativeStatus::Unsupported,
494 negativeMessage("Hessian bilinear variance",
495 raw, static_cast<int>(b)));
496 covariance(r, r) = *variance;
497 }
498 out[b] = std::move(covariance);
499 } catch (const std::length_error& e) {
500 return refuse(DerivativeStatus::Unsupported, e.what());
501 } catch (const std::range_error& e) {
502 return refuse(DerivativeStatus::Unsupported, e.what());
503 }
504 }
505 covariance = std::move(out);
506 return report;
507}
508
510 GaussianProcessRegression& gp, const Eigen::MatrixXd& points,
511 const std::vector<Eigen::MatrixXd>& directions,
512 const DerivativeOptions& options, std::vector<Eigen::VectorXd>& variances)
513{
514 const std::size_t count = static_cast<std::size_t>(points.rows());
515 if (directions.size() != count)
517 "one direction block per point");
518 for (const auto& block: directions)
519 if (block.rows() == 0 || block.cols() != points.cols() ||
520 !block.allFinite())
522 "direction blocks must be finite k x d");
523 DerivativeReport report = admit(gp, points, options);
524 if (!report.ok()) return report;
525 const double step = varianceStep(options);
526 std::vector<Eigen::VectorXd> out(count);
527 for (std::size_t b = 0; b < count; ++b) {
528 const Eigen::VectorXd x = points.row(static_cast<Eigen::Index>(b));
529 Eigen::MatrixXd vectors = directions[b];
530 if (options.project_rigid) {
531 const Eigen::MatrixXd P = rigidProjector(x, gp.getAtomsConfig());
532 vectors = (vectors * P).eval();
533 }
534 out[b].resize(vectors.rows());
535 for (Eigen::Index k = 0; k < vectors.rows(); ++k) {
536 try {
537 const Stencil stencil =
538 stencilFunctionals(x, vectors.row(k), vectors.row(k), step);
539 const double raw = stencilCovariance(gp, stencil)(0, 0);
540 const auto variance =
541 raw < 0.0 ? roundoffVariance(
542 raw, stencilPriorScale(gp, stencil, 0))
543 : std::optional<double>(raw);
544 if (!variance)
545 return refuse(DerivativeStatus::Unsupported,
546 negativeMessage("Hessian bilinear variance",
547 raw, static_cast<int>(b)));
548 out[b](k) = *variance;
549 } catch (const std::length_error& e) {
550 return refuse(DerivativeStatus::Unsupported, e.what());
551 } catch (const std::range_error& e) {
552 return refuse(DerivativeStatus::Unsupported, e.what());
553 }
554 }
555 }
556 variances = std::move(out);
557 return report;
558}
559
561 GaussianProcessRegression& gp, const Eigen::MatrixXd& points,
562 const std::vector<Eigen::MatrixXd>& weights,
563 const DerivativeOptions& options, Eigen::VectorXd& variances)
564{
565 const std::size_t count = static_cast<std::size_t>(points.rows());
566 if (weights.size() != count)
568 "one weight matrix per point");
569 for (const auto& A: weights)
570 if (A.rows() != points.cols() || A.cols() != points.cols() ||
571 !A.allFinite() ||
572 (A - A.transpose()).cwiseAbs().maxCoeff() >
573 64.0 * std::numeric_limits<double>::epsilon() *
574 std::max(1.0, A.cwiseAbs().maxCoeff()))
576 "weight matrices must be finite, symmetric d x d");
577 DerivativeReport report = admit(gp, points, options);
578 if (!report.ok()) return report;
579 const double step = varianceStep(options);
580 Eigen::VectorXd out(points.rows());
581 for (std::size_t b = 0; b < count; ++b) {
582 const Eigen::VectorXd x = points.row(static_cast<Eigen::Index>(b));
583 Eigen::MatrixXd A = 0.5 * (weights[b] + weights[b].transpose());
584 if (options.project_rigid) {
585 const Eigen::MatrixXd P = rigidProjector(x, gp.getAtomsConfig());
586 A = (P * A * P).eval();
587 }
588 const LongMatrix Al = A.cast<long double>();
589 const Eigen::SelfAdjointEigenSolver<LongMatrix> spectrum(Al);
590 if (spectrum.info() != Eigen::Success)
592 "weight matrix has no eigendecomposition");
593 const long double cut =
594 64.0L *
595 static_cast<long double>(std::numeric_limits<double>::epsilon()) *
596 spectrum.eigenvalues().cwiseAbs().maxCoeff();
597 std::vector<Eigen::Index> kept;
598 for (Eigen::Index k = 0; k < A.rows(); ++k)
599 if (std::abs(spectrum.eigenvalues()(k)) > cut) kept.push_back(k);
600 if (kept.empty()) {
601 out(static_cast<Eigen::Index>(b)) = 0.0;
602 continue;
603 }
604 const Eigen::Index r = static_cast<Eigen::Index>(kept.size());
605 Eigen::MatrixXd modes(r, A.rows());
606 Eigen::Matrix<long double, Eigen::Dynamic, 1> lambda(r);
607 for (Eigen::Index k = 0; k < r; ++k) {
608 const Eigen::Index idx = kept[static_cast<std::size_t>(k)];
609 Eigen::Matrix<long double, Eigen::Dynamic, 1> mode =
610 spectrum.eigenvectors().col(idx);
611 Eigen::Index pivot = 0;
612 mode.cwiseAbs().maxCoeff(&pivot);
613 if (mode(pivot) < 0.0L) mode = -mode;
614 modes.row(k) = mode.transpose().cast<double>();
615 lambda(k) = spectrum.eigenvalues()(idx);
616 }
617 try {
618 const Stencil stencil = stencilFunctionals(x, modes, modes, step);
619 const Eigen::MatrixXd pairs = stencilCovariance(gp, stencil);
620 // tr(A H) = sum_k lambda_k u_k^T H u_k: the diagonal pairs
621 // k * r + k.
622 long double total = 0.0L;
623 for (Eigen::Index k = 0; k < r; ++k)
624 for (Eigen::Index l = 0; l < r; ++l)
625 total +=
626 lambda(k) * lambda(l) *
627 static_cast<long double>(pairs(k * r + k, l * r + l));
628 const double raw = representable(total, "Hessian trace variance");
629 std::optional<double> variance(raw);
630 if (raw < 0.0) {
631 // abs(sum_kl lambda_k lambda_l C_kl) <=
632 // (sum_k abs(lambda_k) s_k)^2 for each mode's prior root s_k.
633 const auto roots = stencilPriorRoots(gp, stencil);
634 long double bound = 0.0L;
635 for (Eigen::Index k = 0; k < r; ++k)
636 bound += std::abs(lambda(k)) * roots(k * r + k);
637 variance =
638 roundoffVariance(raw, static_cast<double>(bound * bound));
639 }
640 if (!variance)
641 return refuse(DerivativeStatus::Unsupported,
642 negativeMessage("Hessian trace variance", raw,
643 static_cast<int>(b)));
644 out(static_cast<Eigen::Index>(b)) = *variance;
645 } catch (const std::length_error& e) {
646 return refuse(DerivativeStatus::Unsupported, e.what());
647 } catch (const std::range_error& e) {
648 return refuse(DerivativeStatus::Unsupported, e.what());
649 }
650 }
651 variances = std::move(out);
652 return report;
653}
654
656 const Eigen::MatrixXd& points,
657 const DerivativeOptions& options,
658 Eigen::VectorXd& energy_variance,
659 Eigen::MatrixXd& gradient_variance)
660{
661 DerivativeReport report = admit(gp, points, options);
662 if (!report.ok()) return report;
663 Eigen::VectorXd e(points.rows());
664 Eigen::MatrixXd g(points.rows(), points.cols());
665 for (Eigen::Index b = 0; b < points.rows(); ++b) {
666 Observation query;
667 query.R = points.row(b);
669 if (query.E.size() < 1 || query.G.size() != points.cols() ||
670 !query.G.allFinite() || !std::isfinite(query.E(0, 0)))
671 return refuse(DerivativeStatus::Unsupported,
672 "posterior variance is not finite");
673 e(b) = query.E(0, 0);
674 g.row(b) = query.G.row(0);
675 }
676 energy_variance = std::move(e);
677 gradient_variance = std::move(g);
678 return report;
679}
680
682 const Eigen::VectorXd& point,
683 const Eigen::MatrixXd& hessian)
684{
685 gp.setConditionedHessian(point, hessian);
686}
687
689{
690 gp.clearConditionedHessians();
691}
692
694 const Eigen::VectorXd& point,
695 Eigen::MatrixXd& hessian_out)
696{
697 return gp.findConditionedHessian(point, hessian_out);
698}
699
702 const Observation& added, const Eigen::MatrixXd* fixed_hessian,
703 const HessianAction* hvp, const Eigen::MatrixXd& queries,
704 const DerivativeOptions& options, Eigen::VectorXd& energy,
705 Eigen::MatrixXd& gradient, Eigen::VectorXd& energy_variance,
706 Eigen::MatrixXd& gradient_variance)
707{
708 if (!gp.isDecomposedSuccessfully() || training.R.rows() == 0)
709 return refuse(DerivativeStatus::NotTrained, "model not trained");
710 const Eigen::Index dof = training.R.cols();
711 if (added.R.rows() == 0 || added.R.cols() != dof ||
712 added.G.rows() != added.R.rows() || added.G.cols() != dof ||
713 added.E.size() != added.R.rows() || !added.R.allFinite() ||
714 !added.G.allFinite() || !added.E.allFinite())
716 "added rows need finite positions, energies and "
717 "gradients of the training dimension");
718 if (queries.rows() == 0 || queries.cols() != dof || !queries.allFinite())
720 "queries must be finite rows of the training dimension");
721 if (!knownUnits(options))
722 return refuse(DerivativeStatus::InvalidArgument, "unknown unit tag");
723 if (!std::isfinite(options.max_energy_std) ||
724 !std::isfinite(options.variance_step))
726 "non-finite option value");
727
728 const bool has_hvp = hvp != nullptr && static_cast<bool>(*hvp);
729 if (hvp != nullptr && !has_hvp)
731 "fixed-point HVP callback is empty");
732 if (fixed_hessian != nullptr && has_hvp)
734 "specify at most one of fixed_hessian and hvp");
735
736 Eigen::MatrixXd validated_hessian;
737 const bool has_fixed_curvature = (fixed_hessian != nullptr) || has_hvp;
738 if (has_fixed_curvature) {
739 if (added.R.rows() != 1)
741 "fixed-point Hessian requires a single added point "
742 "(n_new == 1)");
743 if (fixed_hessian != nullptr) {
744 if (fixed_hessian->rows() != dof || fixed_hessian->cols() != dof)
746 "fixed-point Hessian must have shape d x d");
747 if (!fixed_hessian->allFinite())
749 "fixed-point Hessian must be finite");
750 validated_hessian = *fixed_hessian;
751 } else {
752 validated_hessian.resize(dof, dof);
753 Eigen::VectorXd col;
754 for (Eigen::Index j = 0; j < dof; ++j) {
755 col.resize(0);
756 if (!(*hvp)(Eigen::VectorXd::Unit(dof, j), col) ||
757 col.size() != dof || !col.allFinite())
759 "fixed-point HVP callback returned a "
760 "non-finite or mis-sized vector");
761 validated_hessian.col(j) = col;
762 }
763 }
764 const double scale =
765 std::max(1.0, validated_hessian.cwiseAbs().maxCoeff());
766 if ((validated_hessian - validated_hessian.transpose())
767 .cwiseAbs()
768 .maxCoeff() > 1e-10 * scale)
769 return refuse(
771 "fixed-point Hessian or HVP operator is not symmetric");
772 validated_hessian =
773 0.5 * (validated_hessian + validated_hessian.transpose()).eval();
774 }
775
776 Observation combined = training;
777 combined.append(added);
778 TrainingRollback rollback(gp, training);
779 const bool appended = gp.appendFixedHyperparameters(combined);
780 if (!appended) {
781 gp.updateModelWithFullData(combined);
782 if (!gp.isDecomposedSuccessfully()) {
783 return refuse(DerivativeStatus::Unsupported,
784 "posterior cannot be refactored with the added rows");
785 }
786 }
787 Eigen::VectorXd e(queries.rows());
788 Eigen::MatrixXd g(queries.rows(), dof);
789 Eigen::VectorXd ve;
790 Eigen::MatrixXd vg;
791 for (Eigen::Index b = 0; b < queries.rows(); ++b) {
792 Observation query;
793 query.R = queries.row(b);
795 if (query.E.size() < 1 || query.G.size() != dof) {
796 return refuse(DerivativeStatus::Unsupported,
797 "posterior mean is unavailable");
798 }
799 e(b) = query.E(0, 0);
800 g.row(b) = query.G.row(0);
801 }
802 DerivativeOptions unchecked = options;
803 unchecked.max_energy_std = 0.0;
804 unchecked.project_rigid = false;
805 DerivativeReport report =
806 posteriorVariances(gp, queries, unchecked, ve, vg);
807 if (!report.ok()) return report;
808 rollback.release();
809 training = std::move(combined);
810 if (has_fixed_curvature)
811 gp.setConditionedHessian(added.R.row(0).transpose(), validated_hessian);
812 report.projected = false;
813 report.factor_appended = appended ? 1 : 0;
814 if (options.max_energy_std > 0.0 &&
815 report.max_energy_std > options.max_energy_std) {
817 report.message =
818 "a query is outside the conditioned posterior's "
819 "support; the rows were appended";
820 return report;
821 }
822 energy = std::move(e);
823 gradient = std::move(g);
824 energy_variance = std::move(ve);
825 gradient_variance = std::move(vg);
826 return report;
827}
828
830 Observation& training, const Observation& added,
831 const Eigen::MatrixXd& queries,
832 const DerivativeOptions& options,
833 Eigen::VectorXd& energy,
834 Eigen::MatrixXd& gradient,
835 Eigen::VectorXd& energy_variance,
836 Eigen::MatrixXd& gradient_variance)
837{
838 return conditionFixed(
839 gp, training, added, static_cast<const Eigen::MatrixXd*>(nullptr),
840 static_cast<const HessianAction*>(nullptr), queries, options, energy,
841 gradient, energy_variance, gradient_variance);
842}
843
846 const Observation& added, const Eigen::MatrixXd& fixed_hessian,
847 const Eigen::MatrixXd& queries, const DerivativeOptions& options,
848 Eigen::VectorXd& energy, Eigen::MatrixXd& gradient,
849 Eigen::VectorXd& energy_variance, Eigen::MatrixXd& gradient_variance)
850{
851 return conditionFixed(gp, training, added, &fixed_hessian,
852 static_cast<const HessianAction*>(nullptr), queries,
853 options, energy, gradient, energy_variance,
854 gradient_variance);
855}
856
859 const Observation& added, const HessianAction& hvp,
860 const Eigen::MatrixXd& queries, const DerivativeOptions& options,
861 Eigen::VectorXd& energy, Eigen::MatrixXd& gradient,
862 Eigen::VectorXd& energy_variance, Eigen::MatrixXd& gradient_variance)
863{
864 return conditionFixed(
865 gp, training, added, static_cast<const Eigen::MatrixXd*>(nullptr), &hvp,
866 queries, options, energy, gradient, energy_variance, gradient_variance);
867}
868
869} // namespace gpr::posterior
@ x
Definition Enums.h:28
void assembleMatrixOfRepetitiveCoordinates(const gpr::Coord &coord, gpr::EigenMatrix &matrix, Eigen::VectorXd &ind)
Assemble Eigen matrix with repetitive rows based on provided set of coordinates R.
const Observation & fittedObservations() const noexcept
The observations the current posterior is fitted on.
void evaluateCovarianceMatrix(const EigenMatrix &x1, const EigenMatrix &x2, const Eigen::VectorXd &x1_ind, const Eigen::VectorXd &x2_ind, EigenMatrix &C, bool serial_per_rank=false) const
Evaluate covariance matrix between two input vectors.
void calculateVarianceDispatched(Observation &image1)
std::function< bool(const Eigen::VectorXd &, Eigen::VectorXd &)> MeanHessianAction
void setConditionedHessian(const Eigen::VectorXd &point, const Eigen::MatrixXd &hessian)
void calculatePotentialDispatched(Observation &image1)
Definition Predict.cpp:982
void updateModelWithFullData(const Observation &full_observation)
void calculateObservationPosteriorCovariance(const EigenMatrix &positions, EigenMatrix &K_post, bool allow_hssvd_local=true)
MeanHessianAction prepareAnalyticMeanHessian(const Coord &R)
bool appendFixedHyperparameters(const Observation &full_observation)
bool findConditionedHessian(const Eigen::VectorXd &point, Eigen::MatrixXd &hessian_out) const
const AtomsConfiguration & getAtomsConfig() const
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
int status
Eigen::MatrixXd physicalCurvatureBasis(const gpr::Coord &positions, const gpr::AtomsConfiguration &config, bool exclude_rotations=true, RigidMotionMetric metric=RigidMotionMetric::MassWeighted)
Eigen::MatrixXd massWeightedRigidMotions(const Eigen::VectorXd &positions, const Eigen::VectorXd &masses)
DerivativeReport posteriorVariances(GaussianProcessRegression &gp, const Eigen::MatrixXd &points, const DerivativeOptions &options, Eigen::VectorXd &energy_variance, Eigen::MatrixXd &gradient_variance)
Posterior energy and gradient variance at the rows of points.
DerivativeReport conditionFixed(GaussianProcessRegression &gp, Observation &training, const Observation &added, const Eigen::MatrixXd *fixed_hessian, const HessianAction *hvp, const Eigen::MatrixXd &queries, const DerivativeOptions &options, Eigen::VectorXd &energy, Eigen::MatrixXd &gradient, Eigen::VectorXd &energy_variance, Eigen::MatrixXd &gradient_variance)
Condition on added and optionally record an exact Hessian or Hessian-vector-product callback at the f...
void setConditionedHessian(GaussianProcessRegression &gp, const Eigen::VectorXd &point, const Eigen::MatrixXd &hessian)
Record a user-supplied exact Hessian conditioned at point.
DerivativeReport hessianBilinearCovariance(GaussianProcessRegression &gp, const Eigen::MatrixXd &points, const std::vector< Eigen::MatrixXd > &left, const std::vector< Eigen::MatrixXd > &right, const DerivativeOptions &options, std::vector< Eigen::MatrixXd > &covariance)
Posterior covariance of M_ij = v_i^T H w_j at each point. left[b] holds the v_i as rows and right[b] ...
DerivativeReport hessianTraceVariance(GaussianProcessRegression &gp, const Eigen::MatrixXd &points, const std::vector< Eigen::MatrixXd > &weights, const DerivativeOptions &options, Eigen::VectorXd &variances)
Posterior variance of tr(A dH) at each point for a symmetric A per point, the same estimate as hessia...
DerivativeReport meanHessianActions(GaussianProcessRegression &gp, const Eigen::MatrixXd &points, const std::vector< Eigen::MatrixXd > &directions, const DerivativeOptions &options, std::vector< Eigen::MatrixXd > &actions)
Posterior-mean Hessian actions. directions[b] holds k rows, each one vector at point b; actions[b] re...
void clearConditionedHessians(GaussianProcessRegression &gp) noexcept
Clear all conditioned exact Hessians stored on gp.
constexpr double kNegativeVarianceTolerance
Relative tolerance under which a negative posterior variance is binary64 round-off.
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,...
Eigen::MatrixXd rigidGenerators(const Eigen::VectorXd &positions)
Unit rigid generators of 3N coordinates as columns: three translations, then rotations about the x,...
constexpr double defaultVarianceStep() noexcept
Default finite-difference step for posterior curvature variance.
Eigen::MatrixXd rigidProjector(const Eigen::VectorXd &positions, const AtomsConfiguration &config)
Orthogonal projector onto the physical vibrational complement of the rigid motions of positions under...
std::function< bool(const Eigen::VectorXd &direction, Eigen::VectorXd &hv)> HessianAction
Exact Hessian-vector-product callback at a fixed point: writes H(x) * v into hv and returns true on s...
bool findConditionedHessian(const GaussianProcessRegression &gp, const Eigen::VectorXd &point, Eigen::MatrixXd &hessian_out)
Look up a conditioned exact Hessian at point.
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,...
DerivativeStatus
Outcome of a derivative primitive. The C API maps each value to one status code; nothing here returns...
@ Unsupported
The fitted mean has no analytic Hessian contraction.
std::optional< double > roundoffVariance(double variance, double prior_scale) noexcept
variance when it is finite and nonnegative, zero when it is negative by at most kNegativeVarianceTole...
FieldMatrixd Coord
Definition Macros.h:35
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
Stores configurations of all atoms in the system.
Definition Structures.h:832
Observation data: energy, gradient and positions.
FieldMatrixd E
void append(const Observation &other)
Options for batched posterior derivative primitives.
Report returned by a batched posterior derivative primitive.
bool ok() const noexcept
True when the call succeeded.