Loading...
Searching...
No Matches
gpr::posterior Namespace Reference

Classes

struct  DerivativeOptions
 Options for batched posterior derivative primitives. More...
struct  DerivativeReport
 Report returned by a batched posterior derivative primitive. More...

Typedefs

using HessianAction
 Exact Hessian-vector-product callback at a fixed point: writes H(x) * v into hv and returns true on success.

Enumerations

enum class  DerivativeStatus {
  Ok , InvalidArgument , NotTrained , Unsupported ,
  OutOfSupport
}
 Outcome of a derivative primitive. The C API maps each value to one status code; nothing here returns a NaN in place of a failure. More...
enum class  EnergyUnit {
  Native = 0 , Ev = 1 , Hartree = 2 , KcalPerMol = 3 ,
  KjPerMol = 4
}
 Unit tags carried through the primitives. They name the units the GP was trained in; no value is converted. More...
enum class  LengthUnit { Native = 0 , Angstrom = 1 , Bohr = 2 , Nanometer = 3 }
 Length unit tags carried through the derivative primitives. More...

Functions

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 kNegativeVarianceTolerance * prior_scale, and empty otherwise. An empty result is refused with Unsupported by every primitive: a materially negative variance is never in support and never a converged spread. A prior_scale that is not finite and positive admits no negative value.
Eigen::MatrixXd rigidGenerators (const Eigen::VectorXd &positions)
 Unit rigid generators of 3N coordinates as columns: three translations, then rotations about the x, y and z axes through the centroid. A rotation that does not move any atom (one atom, or an axis a linear geometry lies on) is a zero column.
Eigen::MatrixXd rigidProjector (const Eigen::VectorXd &positions, const AtomsConfiguration &config)
 Orthogonal projector onto the physical vibrational complement of the rigid motions of positions under config.
Eigen::MatrixXd rigidProjector (const Eigen::VectorXd &positions)
 I - Q Q^T for an orthonormal basis Q of the nonzero rigid generators.
DerivativeReport meanHessians (GaussianProcessRegression &gp, const Eigen::MatrixXd &points, const DerivativeOptions &options, std::vector< Eigen::MatrixXd > &hessians, Eigen::MatrixXd *residuals=nullptr)
 Full posterior-mean Hessians at the rows of points, symmetrized. residuals, when given, receives one row per point: ||H t|| for the six unit generators of rigidGenerators, -1 where a generator vanishes.
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] receives H(x_b) v as the same k rows.
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] the w_j. covariance[b] is (kl kr)^2 with entry index i * kr + j. The curvature is the central difference of the posterior gradient process along each w_j, so this is the covariance of that stencil: a probabilistic estimate with O(h^2) truncation in variance_step, not a bound. Forms the 2 kr (d + 1) joint posterior covariance block per point (O(kr^2 d^2) memory). The three Hessian uncertainty functions refuse with Unsupported, outputs untouched, when a result overflows, is NaN, or flushes a nonzero value below the normal double range (direction norms far from 1 scale it by their fourth power).
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, avoiding a k^2 covariance matrix when callers need only each mode's variance.
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 hessianBilinearCovariance on the eigenvectors of A (O(rank(A)^2 d^2) joint-covariance memory).
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.
void setConditionedHessian (GaussianProcessRegression &gp, const Eigen::VectorXd &point, const Eigen::MatrixXd &hessian)
 Record a user-supplied exact Hessian conditioned at point.
void clearConditionedHessians (GaussianProcessRegression &gp) noexcept
 Clear all conditioned exact Hessians stored on gp.
bool findConditionedHessian (const GaussianProcessRegression &gp, const Eigen::VectorXd &point, Eigen::MatrixXd &hessian_out)
 Look up a conditioned exact Hessian at point.
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 fixed point (added.R.rows() == 1). An invalid shape, non-finite entry, or asymmetric Hessian / HVP is rejected with DerivativeStatus::InvalidArgument before mutating gp or training (no silent fallback to GP curvature).
DerivativeReport conditionFixed (GaussianProcessRegression &gp, Observation &training, const Observation &added, const Eigen::MatrixXd &queries, const DerivativeOptions &options, Eigen::VectorXd &energy, Eigen::MatrixXd &gradient, Eigen::VectorXd &energy_variance, Eigen::MatrixXd &gradient_variance)
 Condition the fitted posterior on the rows of added at its current hyperparameters, then predict mean and variance at queries. The training factor is bordered in place when the backend allows it and refactored at the same hyperparameters otherwise; the report says which. Neither refits a hyperparameter. training is the observation set the posterior was fitted on; it is extended whenever the rows are taken, including an OutOfSupport return for the queries.
DerivativeReport conditionFixed (GaussianProcessRegression &gp, Observation &training, const Observation &added, const Eigen::MatrixXd &fixed_hessian, 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 record an exact Hessian at the fixed point.
DerivativeReport conditionFixed (GaussianProcessRegression &gp, Observation &training, const Observation &added, 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 record an HVP callback at the fixed point.
constexpr double defaultVarianceStep () noexcept
 Default finite-difference step for posterior curvature variance.

Variables

constexpr double kNegativeVarianceTolerance = 0x1p-26
 Relative tolerance under which a negative posterior variance is binary64 round-off.

Typedef Documentation

◆ HessianAction

Initial value:
std::function<bool(const Eigen::VectorXd& direction, Eigen::VectorXd& hv)>

Exact Hessian-vector-product callback at a fixed point: writes H(x) * v into hv and returns true on success.

Definition at line 201 of file PosteriorDerivatives.h.

Enumeration Type Documentation

◆ DerivativeStatus

Outcome of a derivative primitive. The C API maps each value to one status code; nothing here returns a NaN in place of a failure.

Enumerator
Ok 
InvalidArgument 
NotTrained 
Unsupported 

The fitted mean has no analytic Hessian contraction.

OutOfSupport 

A point's posterior energy standard deviation exceeds the caller's threshold.

Definition at line 19 of file PosteriorDerivatives.h.

◆ EnergyUnit

enum class gpr::posterior::EnergyUnit
strong

Unit tags carried through the primitives. They name the units the GP was trained in; no value is converted.

Enumerator
Native 
Ev 
Hartree 
KcalPerMol 
KjPerMol 

Definition at line 32 of file PosteriorDerivatives.h.

◆ LengthUnit

enum class gpr::posterior::LengthUnit
strong

Length unit tags carried through the derivative primitives.

Enumerator
Native 
Angstrom 
Bohr 
Nanometer 

Definition at line 41 of file PosteriorDerivatives.h.

Function Documentation

◆ clearConditionedHessians()

void gpr::posterior::clearConditionedHessians ( GaussianProcessRegression & gp)
noexcept

Clear all conditioned exact Hessians stored on gp.

Definition at line 688 of file PosteriorDerivatives.cpp.

◆ conditionFixed() [1/4]

DerivativeReport gpr::posterior::conditionFixed ( GaussianProcessRegression & gp,
Observation & training,
const Observation & added,
const Eigen::MatrixXd & fixed_hessian,
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 record an exact Hessian at the fixed point.

Definition at line 844 of file PosteriorDerivatives.cpp.

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}
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...
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...

◆ conditionFixed() [2/4]

DerivativeReport gpr::posterior::conditionFixed ( GaussianProcessRegression & gp,
Observation & training,
const Observation & added,
const Eigen::MatrixXd & queries,
const DerivativeOptions & options,
Eigen::VectorXd & energy,
Eigen::MatrixXd & gradient,
Eigen::VectorXd & energy_variance,
Eigen::MatrixXd & gradient_variance )

Condition the fitted posterior on the rows of added at its current hyperparameters, then predict mean and variance at queries. The training factor is bordered in place when the backend allows it and refactored at the same hyperparameters otherwise; the report says which. Neither refits a hyperparameter. training is the observation set the posterior was fitted on; it is extended whenever the rows are taken, including an OutOfSupport return for the queries.

Definition at line 829 of file PosteriorDerivatives.cpp.

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}

◆ conditionFixed() [3/4]

DerivativeReport gpr::posterior::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 fixed point (added.R.rows() == 1). An invalid shape, non-finite entry, or asymmetric Hessian / HVP is rejected with DerivativeStatus::InvalidArgument before mutating gp or training (no silent fallback to GP curvature).

Definition at line 700 of file PosteriorDerivatives.cpp.

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) {
816 report.status = DerivativeStatus::OutOfSupport;
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}
void setConditionedHessian(const Eigen::VectorXd &point, const Eigen::MatrixXd &hessian)
void calculatePotentialDispatched(Observation &image1)
Definition Predict.cpp:982
void updateModelWithFullData(const Observation &full_observation)
bool appendFixedHyperparameters(const Observation &full_observation)
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.
@ Unsupported
The fitted mean has no analytic Hessian contraction.
FieldMatrixd E
void append(const Observation &other)
Options for batched posterior derivative primitives.
Report returned by a batched posterior derivative primitive.

◆ conditionFixed() [4/4]

DerivativeReport gpr::posterior::conditionFixed ( GaussianProcessRegression & gp,
Observation & training,
const Observation & added,
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 record an HVP callback at the fixed point.

Definition at line 857 of file PosteriorDerivatives.cpp.

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}

◆ defaultVarianceStep()

double gpr::posterior::defaultVarianceStep ( )
inlinenodiscardconstexprnoexcept

Default finite-difference step for posterior curvature variance.

Definition at line 60 of file PosteriorDerivatives.h.

61{
62 return 1e-3;
63}

◆ findConditionedHessian()

bool gpr::posterior::findConditionedHessian ( const GaussianProcessRegression & gp,
const Eigen::VectorXd & point,
Eigen::MatrixXd & hessian_out )
nodiscard

Look up a conditioned exact Hessian at point.

Definition at line 693 of file PosteriorDerivatives.cpp.

696{
697 return gp.findConditionedHessian(point, hessian_out);
698}
bool findConditionedHessian(const Eigen::VectorXd &point, Eigen::MatrixXd &hessian_out) const

◆ hessianBilinearCovariance()

DerivativeReport gpr::posterior::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] the w_j. covariance[b] is (kl kr)^2 with entry index i * kr + j. The curvature is the central difference of the posterior gradient process along each w_j, so this is the covariance of that stencil: a probabilistic estimate with O(h^2) truncation in variance_step, not a bound. Forms the 2 kr (d + 1) joint posterior covariance block per point (O(kr^2 d^2) memory). The three Hessian uncertainty functions refuse with Unsupported, outputs untouched, when a result overflows, is NaN, or flushes a nonzero value below the normal double range (direction norms far from 1 scale it by their fourth power).

Definition at line 454 of file PosteriorDerivatives.cpp.

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}
@ x
Definition Enums.h:28
const AtomsConfiguration & getAtomsConfig() const
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
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::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...
bool ok() const noexcept
True when the call succeeded.

◆ hessianBilinearVariances()

DerivativeReport gpr::posterior::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, avoiding a k^2 covariance matrix when callers need only each mode's variance.

Definition at line 509 of file PosteriorDerivatives.cpp.

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}
STL namespace.

◆ hessianTraceVariance()

DerivativeReport gpr::posterior::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 hessianBilinearCovariance on the eigenvectors of A (O(rank(A)^2 d^2) joint-covariance memory).

Definition at line 560 of file PosteriorDerivatives.cpp.

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}
double variance(const Weights &w, const Matrix &covariance)

◆ meanHessianActions()

DerivativeReport gpr::posterior::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] receives H(x_b) v as the same k rows.

Definition at line 418 of file PosteriorDerivatives.cpp.

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}

◆ meanHessians()

DerivativeReport gpr::posterior::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, receives one row per point: ||H t|| for the six unit generators of rigidGenerators, -1 where a generator vanishes.

Definition at line 369 of file PosteriorDerivatives.cpp.

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}
Eigen::MatrixXd rigidGenerators(const Eigen::VectorXd &positions)
Unit rigid generators of 3N coordinates as columns: three translations, then rotations about the x,...

◆ posteriorVariances()

DerivativeReport gpr::posterior::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.

Definition at line 655 of file PosteriorDerivatives.cpp.

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}
void calculateVarianceDispatched(Observation &image1)
Observation data: energy, gradient and positions.

◆ rigidGenerators()

Eigen::MatrixXd gpr::posterior::rigidGenerators ( const Eigen::VectorXd & positions)
nodiscard

Unit rigid generators of 3N coordinates as columns: three translations, then rotations about the x, y and z axes through the centroid. A rotation that does not move any atom (one atom, or an axis a linear geometry lies on) is a zero column.

Definition at line 328 of file PosteriorDerivatives.cpp.

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}
Eigen::MatrixXd massWeightedRigidMotions(const Eigen::VectorXd &positions, const Eigen::VectorXd &masses)

◆ rigidProjector() [1/2]

Eigen::MatrixXd gpr::posterior::rigidProjector ( const Eigen::VectorXd & positions)
nodiscard

I - Q Q^T for an orthonormal basis Q of the nonzero rigid generators.

Definition at line 364 of file PosteriorDerivatives.cpp.

365{
366 return rigidProjector(positions, AtomsConfiguration{});
367}
Stores configurations of all atoms in the system.
Definition Structures.h:832

◆ rigidProjector() [2/2]

Eigen::MatrixXd gpr::posterior::rigidProjector ( const Eigen::VectorXd & positions,
const AtomsConfiguration & config )
nodiscard

Orthogonal projector onto the physical vibrational complement of the rigid motions of positions under config.

Definition at line 349 of file PosteriorDerivatives.cpp.

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}
Eigen::MatrixXd physicalCurvatureBasis(const gpr::Coord &positions, const gpr::AtomsConfiguration &config, bool exclude_rotations=true, RigidMotionMetric metric=RigidMotionMetric::MassWeighted)
FieldMatrixd Coord
Definition Macros.h:35

◆ roundoffVariance()

std::optional< double > gpr::posterior::roundoffVariance ( double variance,
double prior_scale )
nodiscardnoexcept

variance when it is finite and nonnegative, zero when it is negative by at most kNegativeVarianceTolerance * prior_scale, and empty otherwise. An empty result is refused with Unsupported by every primitive: a materially negative variance is never in support and never a converged spread. A prior_scale that is not finite and positive admits no negative value.

Definition at line 317 of file PosteriorDerivatives.cpp.

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}
constexpr double kNegativeVarianceTolerance
Relative tolerance under which a negative posterior variance is binary64 round-off.

◆ setConditionedHessian()

void gpr::posterior::setConditionedHessian ( GaussianProcessRegression & gp,
const Eigen::VectorXd & point,
const Eigen::MatrixXd & hessian )

Record a user-supplied exact Hessian conditioned at point.

Definition at line 681 of file PosteriorDerivatives.cpp.

684{
685 gp.setConditionedHessian(point, hessian);
686}

Variable Documentation

◆ kNegativeVarianceTolerance

double gpr::posterior::kNegativeVarianceTolerance = 0x1p-26
inlineconstexpr

Relative tolerance under which a negative posterior variance is binary64 round-off.

A posterior variance is prior - k^T K^{-1} k. Its round-off is about eps cond(K) times the prior scale of the same functional: the background kernel's energy variance at the point for an energy, and (sum_i abs(w_i) sqrt(K_ii))^2 for a stencil functional w, the Cauchy-Schwarz bound of abs(w^T K w) over the prior marginals K_ii. sqrt(eps) admits cond(K) up to about 6.7e7. This is the only place a negative variance may become zero; see roundoffVariance.

Definition at line 75 of file PosteriorDerivatives.h.