Loading...
Searching...
No Matches
gpr::bo::FreeEnergySurrogate Class Reference

#include <gpr/bo/FreeEnergySurrogate.h>

Public Member Functions

 FreeEnergySurrogate (int dimension, const FreeEnergySurrogateConfig &config)
int dimension () const noexcept
int observationCount () const noexcept
bool trained () const noexcept
const FreeEnergySurrogateConfig & config () const noexcept
void train (const FreeEnergyObservations &observations)
double marginalObjective (const FreeEnergyObservations &observations, const Eigen::VectorXd &log_hyperparameters, Eigen::VectorXd *gradient) const
double mapObjective (const FreeEnergyObservations &observations, const Eigen::VectorXd &log_hyperparameters, Eigen::VectorXd *gradient) const
void predict (const Eigen::MatrixXd &queries, Eigen::VectorXd &value, Eigen::MatrixXd *gradient, Eigen::VectorXd *variance) const
Eigen::MatrixXd meanHessian (const Eigen::VectorXd &point) const
 Posterior mean Hessian of F at one point.
FreeEnergyPathPosterior pathPosterior (const Eigen::MatrixXd &path) const
KramersRateSummary pathRate (const Eigen::MatrixXd &path, int reactant, int product, const KramersRateConfig &config) const
const Eigen::VectorXd & lengthscales () const noexcept
double signalVariance () const noexcept
double priorMean () const noexcept
const Eigen::VectorXd & gradientNoiseVariance () const noexcept
const FreeEnergyFitReport & fitReport () const noexcept

Static Public Member Functions

static double priorCovariance (const std::vector< int > &left_axes, const Eigen::VectorXd &x, const std::vector< int > &right_axes, const Eigen::VectorXd &y, const Eigen::VectorXd &lengthscales, double signal_variance)

Detailed Description

Definition at line 167 of file FreeEnergySurrogate.h.

Constructor & Destructor Documentation

◆ FreeEnergySurrogate()

gpr::bo::FreeEnergySurrogate::FreeEnergySurrogate ( int dimension,
const FreeEnergySurrogateConfig & config )

Definition at line 379 of file FreeEnergySurrogate.cpp.

381 : dimension_(dimension), config_(config)
382{
383 if (dimension_ <= 0) {
384 throw std::invalid_argument("free-energy dimension must be positive");
385 }
386 const auto non_negative = [](double value) {
387 return value >= 0.0 && std::isfinite(value);
388 };
389 if (!non_negative(config_.noise_variance) ||
390 !non_negative(config_.jitter_variance) ||
391 !non_negative(config_.signal_variance)) {
392 throw std::invalid_argument(
393 "noise, jitter and signal variances must be non-negative");
394 }
395 if (config_.gradient_noise_variance.size() != 0) {
396 if (config_.gradient_noise_variance.size() != dimension_) {
397 throw std::invalid_argument(
398 "gradient noise variances need one entry per coordinate");
399 }
400 if (!config_.gradient_noise_variance.allFinite() ||
401 (config_.gradient_noise_variance.array() < 0.0).any()) {
402 throw std::invalid_argument(
403 "gradient noise variances must be non-negative and finite");
404 }
405 }
406 if (config_.max_iter < 0 || !(config_.tol_func > 0.0) ||
407 !(config_.tol_sol > 0.0) || !std::isfinite(config_.tol_func) ||
408 !std::isfinite(config_.tol_sol) || config_.report_level < 0 ||
409 config_.report_level > kMaxReportLevel) {
410 throw std::invalid_argument(
411 "optimizer iterations, tolerances or report level are invalid");
412 }
413}
const FreeEnergySurrogateConfig & config() const noexcept

Member Function Documentation

◆ config()

const FreeEnergySurrogateConfig & gpr::bo::FreeEnergySurrogate::config ( ) const
inlinenodiscardnoexcept

Definition at line 183 of file FreeEnergySurrogate.h.

184 {
185 return config_;
186 }

◆ dimension()

int gpr::bo::FreeEnergySurrogate::dimension ( ) const
inlinenodiscardnoexcept

Definition at line 171 of file FreeEnergySurrogate.h.

172 {
173 return dimension_;
174 }

◆ fitReport()

const FreeEnergyFitReport & gpr::bo::FreeEnergySurrogate::fitReport ( ) const
inlinenodiscardnoexcept

Definition at line 268 of file FreeEnergySurrogate.h.

269 {
270 return fit_report_;
271 }

◆ gradientNoiseVariance()

const Eigen::VectorXd & gpr::bo::FreeEnergySurrogate::gradientNoiseVariance ( ) const
inlinenodiscardnoexcept

Variance added to each gradient component in the last train, one entry per coordinate; empty when that train observed no gradient.

Definition at line 264 of file FreeEnergySurrogate.h.

265 {
266 return gradient_noise_variance_;
267 }

◆ lengthscales()

const Eigen::VectorXd & gpr::bo::FreeEnergySurrogate::lengthscales ( ) const
inlinenodiscardnoexcept

Definition at line 250 of file FreeEnergySurrogate.h.

251 {
252 return lengthscales_;
253 }

◆ mapObjective()

double gpr::bo::FreeEnergySurrogate::mapObjective ( const FreeEnergyObservations & observations,
const Eigen::VectorXd & log_hyperparameters,
Eigen::VectorXd * gradient ) const
nodiscard

The objective train() hands to SCG: marginalObjective plus the MAP penalty of funcmin::applyMapPenalty, weighted by the barrier strength min(1e-4 + 1e-3 n, 0.5) for n training rows. The penalty holds a half-Cauchy prior on the signal standard deviation, a half-Student-t (4 degrees of freedom) prior on each length scale over the standard deviation of the points along its coordinates, and, when the signal variance is fitted, a log barrier below a ceiling set by the data. The gradient covers the fitted parameters only (zero for a fixed signal variance). Infinite outside the barrier or where the covariance does not factor.

Definition at line 652 of file FreeEnergySurrogate.cpp.

655{
656 const Eigen::Index expected = config_.ard ? dimension_ + 1 : 2;
657 if (log_hyperparameters.size() != expected) {
658 throw std::invalid_argument(
659 "log hyperparameters hold the signal variance and each length "
660 "scale");
661 }
662 const TrainingSet set = buildTrainingSet(observations, config_, dimension_);
663 const FitStart start = fitStart(observations, set, config_, dimension_);
664 double energy = std::numeric_limits<double>::infinity();
665 Eigen::VectorXd objective_gradient =
666 Eigen::VectorXd::Zero(log_hyperparameters.size());
667 if (funcmin::mapParametersInDomain(log_hyperparameters, start.map)) {
668 MarginalLikelihoodObjective objective(set.design, dimension_);
669 gpr::EnergyAndGradient result(energy, objective_gradient);
670 objective.evaluate(log_hyperparameters, EigenMatrix{},
671 Eigen::VectorXd{}, Eigen::VectorXd{}, result);
672 funcmin::applyMapPenalty(log_hyperparameters, start.map, energy,
673 &objective_gradient);
674 funcmin::projectMapGradient(start.map, objective_gradient);
675 }
676 if (gradient != nullptr) *gradient = objective_gradient;
677 return energy;
678}
void applyMapPenalty(const Eigen::VectorXd &w, const MapObjectiveConfig &cfg, double &energy, Eigen::VectorXd *gradient)
bool mapParametersInDomain(const Eigen::VectorXd &w, const MapObjectiveConfig &cfg)
void projectMapGradient(const MapObjectiveConfig &cfg, Eigen::VectorXd &gradient)
void set(FieldMatrixd &mat, Index_t i, const Eigen::Vector3d &vec)
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20

◆ marginalObjective()

double gpr::bo::FreeEnergySurrogate::marginalObjective ( const FreeEnergyObservations & observations,
const Eigen::VectorXd & log_hyperparameters,
Eigen::VectorXd * gradient ) const
nodiscard

Negative log marginal likelihood of observations at log hyperparameters [log signal variance, log length scale...] (one length scale unless ard), with its gradient when requested. Infinite where the covariance does not factor.

Definition at line 631 of file FreeEnergySurrogate.cpp.

634{
635 const Eigen::Index expected = config_.ard ? dimension_ + 1 : 2;
636 if (log_hyperparameters.size() != expected) {
637 throw std::invalid_argument(
638 "log hyperparameters hold the signal variance and each length "
639 "scale");
640 }
641 const TrainingSet set = buildTrainingSet(observations, config_, dimension_);
642 MarginalLikelihoodObjective objective(set.design, dimension_);
643 double energy = 0.0;
644 Eigen::VectorXd objective_gradient;
645 gpr::EnergyAndGradient result(energy, objective_gradient);
646 objective.evaluate(log_hyperparameters, EigenMatrix{}, Eigen::VectorXd{},
647 Eigen::VectorXd{}, result);
648 if (gradient != nullptr) *gradient = objective_gradient;
649 return energy;
650}

◆ meanHessian()

Eigen::MatrixXd gpr::bo::FreeEnergySurrogate::meanHessian ( const Eigen::VectorXd & point) const
nodiscard

Posterior mean Hessian of F at one point.

Definition at line 874 of file FreeEnergySurrogate.cpp.

876{
877 if (!trained_)
878 throw std::logic_error("free-energy surrogate is not trained");
879 if (point.size() != dimension_ || !point.allFinite()) {
880 throw std::invalid_argument(
881 "Hessian point must be finite and match "
882 "the dimension");
883 }
884 const Eigen::VectorXd scale = profileScale(lengthscales_);
885 const derivatives::RadialMeanExpansion expansion =
886 meanExpansion(points_, gradient_rows_, alpha_, scale, signal_variance_);
887 Eigen::MatrixXd descriptor_hessian;
890 Eigen::VectorXd(point.cwiseProduct(scale)), descriptor_hessian)) {
891 throw std::runtime_error("free-energy mean Hessian is not finite");
892 }
893 return scale.asDiagonal() * descriptor_hessian * scale.asDiagonal();
894}
bool radialMeanHessian(const RadialMeanExpansion &expansion, MeanDerivativeMethod method, const detail::RealVector< Real > &q, detail::RealMatrix< Real > &hessian)
Full Hessian of m at q. False as for radialMeanGradient.

◆ observationCount()

int gpr::bo::FreeEnergySurrogate::observationCount ( ) const
inlinenodiscardnoexcept

Definition at line 175 of file FreeEnergySurrogate.h.

176 {
177 return static_cast<int>(points_.rows());
178 }

◆ pathPosterior()

FreeEnergyPathPosterior gpr::bo::FreeEnergySurrogate::pathPosterior ( const Eigen::MatrixXd & path) const
nodiscard

Definition at line 896 of file FreeEnergySurrogate.cpp.

898{
899 if (!trained_)
900 throw std::logic_error("free-energy surrogate is not trained");
901 if (path.rows() == 0 || path.cols() != dimension_) {
902 throw std::invalid_argument("path dimension differs");
903 }
904 requireFinite(path, "free-energy path");
905 std::vector<std::pair<int, std::vector<int>>> targets;
906 for (Eigen::Index p = 0; p < path.rows(); ++p) {
907 targets.push_back({static_cast<int>(p), {}});
908 for (int i = 0; i < dimension_; ++i) {
909 for (int j = i; j < dimension_; ++j) {
910 targets.push_back({static_cast<int>(p), {i, j}});
911 }
912 }
913 }
914 const std::vector<Functional> rows =
915 trainingFunctionals(points_.rows(), gradient_rows_, dimension_);
916 const Eigen::Index q = static_cast<Eigen::Index>(targets.size());
917 const Eigen::Index n = static_cast<Eigen::Index>(rows.size());
918 EigenMatrix cross(n, q);
919 Eigen::MatrixXd prior(q, q);
920 for (Eigen::Index b = 0; b < q; ++b) {
921 const auto& [point_b, axes_b] = targets[static_cast<std::size_t>(b)];
922 const Eigen::VectorXd y = path.row(point_b).transpose();
923 for (Eigen::Index r = 0; r < n; ++r) {
924 const Functional& row = rows[static_cast<std::size_t>(r)];
925 cross(r, b) =
926 priorCovariance(axesOf(row), points_.row(row.point).transpose(),
927 axes_b, y, lengthscales_, signal_variance_);
928 }
929 for (Eigen::Index a = b; a < q; ++a) {
930 const auto& [point_a, axes_a] =
931 targets[static_cast<std::size_t>(a)];
932 const double value =
933 priorCovariance(axes_a, path.row(point_a).transpose(), axes_b,
934 y, lengthscales_, signal_variance_);
935 prior(a, b) = value;
936 prior(b, a) = value;
937 }
938 }
939 const EigenMatrix explained =
940 gpr::linalg::forward_solve_mat(factor_, cross);
941 Eigen::MatrixXd covariance = prior - explained.transpose() * explained;
942 covariance = 0.5 * (covariance + covariance.transpose()).eval();
943
944 const Eigen::Index stride = 1 + dimension_ * (dimension_ + 1) / 2;
945 FreeEnergyPathPosterior posterior;
946 posterior.dimension = dimension_;
947 posterior.mean.resize(q);
948 Eigen::VectorXd values;
949 predict(path, values, nullptr, nullptr);
950 for (Eigen::Index p = 0; p < path.rows(); ++p) {
951 const Eigen::MatrixXd hessian = meanHessian(path.row(p).transpose());
952 Eigen::Index index = p * stride;
953 posterior.mean[index++] = values[p];
954 for (int i = 0; i < dimension_; ++i) {
955 for (int j = i; j < dimension_; ++j) {
956 posterior.mean[index++] = hessian(i, j);
957 }
958 }
959 }
960 posterior.covariance = std::move(covariance);
961 return posterior;
962}
@ y
Definition Enums.h:28
static double priorCovariance(const std::vector< int > &left_axes, const Eigen::VectorXd &x, const std::vector< int > &right_axes, const Eigen::VectorXd &y, const Eigen::VectorXd &lengthscales, double signal_variance)
void predict(const Eigen::MatrixXd &queries, Eigen::VectorXd &value, Eigen::MatrixXd *gradient, Eigen::VectorXd *variance) const
Eigen::MatrixXd meanHessian(const Eigen::VectorXd &point) const
Posterior mean Hessian of F at one point.
EigenMatrix forward_solve_mat(const EigenMatrix &L, const EigenMatrix &B)
Forward triangular solve with matrix RHS (BLAS equivalent: dtrsm).

◆ pathRate()

KramersRateSummary gpr::bo::FreeEnergySurrogate::pathRate ( const Eigen::MatrixXd & path,
int reactant,
int product,
const KramersRateConfig & config ) const
nodiscard

Overdamped Kramers-Langer rate from reactant to product along path, sampled from the joint posterior of F and its Hessians at the reactant path point and at the saddle of the posterior mean.

The saddle search starts at the interior path point with the highest posterior mean and takes Newton steps on the mean, uphill along the lowest Hessian mode and downhill along the others, each at most half a length scale, for at most 100 steps. It succeeds at a point whose gradient meets config.saddle_tolerance, whose mean Hessian has exactly one negative eigenvalue, and whose nearest point on the path between reactant and product lies within one length scale and is not an end of that stretch; otherwise it throws FreeEnergySaddleNotFoundError. A saddle whose mean F is not above the reactant throws FreeEnergyRateUnsupportedError.

Each draw's rate is abs(kappa) / (2 pi) sqrt(det H_reactant / abs(det H_saddle)) exp(-beta barrier), with kappa the negative eigenvalue of beta D H_saddle and D = diag(config.diffusion).

Definition at line 1164 of file FreeEnergySurrogate.cpp.

1167{
1168 if (!trained_)
1169 throw std::logic_error("free-energy surrogate is not trained");
1170 const int count = static_cast<int>(path.rows());
1171 if (count < 3) {
1172 throw std::invalid_argument("a rate path needs at least three points");
1173 }
1174 if (reactant < 0 || reactant >= count || product < 0 || product >= count ||
1175 std::abs(reactant - product) < 2) {
1176 throw std::invalid_argument(
1177 "reactant and product must be path indices with an interior "
1178 "point between them");
1179 }
1180 if (path.cols() != dimension_) {
1181 throw std::invalid_argument("path dimension differs");
1182 }
1183 requireFinite(path, "free-energy path");
1184 if (config.posterior_samples < 2) {
1185 throw std::invalid_argument(
1186 "a rate needs at least two posterior samples");
1187 }
1188 if (!(config.beta > 0.0) || !std::isfinite(config.beta)) {
1189 throw std::invalid_argument("beta must be positive and finite");
1190 }
1191 if (config.diffusion.size() != dimension_ ||
1192 !(config.diffusion.array() > 0.0).all() ||
1193 !config.diffusion.allFinite()) {
1194 throw std::invalid_argument(
1195 "the diffusion diagonal needs one positive finite entry per "
1196 "coordinate");
1197 }
1198 if (!(config.credible_mass > 0.0) || !(config.credible_mass < 1.0)) {
1199 throw std::invalid_argument("credible mass must lie in (0, 1)");
1200 }
1201 if (!(config.saddle_tolerance > 0.0) ||
1202 !std::isfinite(config.saddle_tolerance)) {
1203 throw std::invalid_argument(
1204 "the saddle tolerance must be positive and finite");
1205 }
1206 double gradient_norm = 0.0;
1207 const Eigen::VectorXd saddle = locateSaddle(
1208 path, reactant, product, config.saddle_tolerance, gradient_norm);
1209 Eigen::MatrixXd points(2, dimension_);
1210 points.row(0) = path.row(reactant);
1211 points.row(1) = saddle.transpose();
1212 const FreeEnergyPathPosterior posterior = pathPosterior(points);
1213 const Eigen::Index stride = 1 + dimension_ * (dimension_ + 1) / 2;
1214 if (!(posterior.mean[stride] - posterior.mean[0] > 0.0)) {
1215 throw FreeEnergyRateUnsupportedError(
1216 "the saddle of the posterior mean is not above the reactant: "
1217 "the barrier is not positive");
1218 }
1219 const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigen(
1220 posterior.covariance);
1221 if (eigen.info() != Eigen::Success) {
1222 throw std::runtime_error(
1223 "free-energy path covariance has no eigendecomposition");
1224 }
1225 const Eigen::MatrixXd root =
1226 eigen.eigenvectors() *
1227 eigen.eigenvalues().cwiseMax(0.0).cwiseSqrt().asDiagonal();
1228 const double two_pi = 2.0 * std::acos(-1.0);
1229 const Eigen::VectorXd diffusion_root = config.diffusion.cwiseSqrt();
1230
1231 SplitMix64 generator(config.seed);
1232 Eigen::VectorXd normal(posterior.mean.size());
1233 std::vector<double> barriers, prefactors, rates;
1234 for (int draw = 0; draw < config.posterior_samples; ++draw) {
1235 fillStandardNormal(generator, normal);
1236 const Eigen::VectorXd sample = posterior.mean + root * normal;
1237 const double barrier = sample[stride] - sample[0];
1238 if (!(barrier > 0.0)) continue;
1239 const Eigen::MatrixXd reactant_hessian =
1240 unpackHessian(sample, 1, dimension_);
1241 const Eigen::VectorXd reactant_modes =
1242 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd>(
1243 reactant_hessian, Eigen::EigenvaluesOnly)
1244 .eigenvalues();
1245 const Eigen::MatrixXd saddle_hessian =
1246 unpackHessian(sample, stride + 1, dimension_);
1247 const Eigen::VectorXd saddle_modes =
1248 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd>(
1249 saddle_hessian, Eigen::EigenvaluesOnly)
1250 .eigenvalues();
1251 if (!(reactant_modes.minCoeff() > 0.0)) continue;
1252 if (!(saddle_modes[0] < 0.0) ||
1253 (dimension_ > 1 && !(saddle_modes[1] > 0.0))) {
1254 continue;
1255 }
1256 // The unstable rate is the negative eigenvalue of beta D H, which
1257 // shares its spectrum with beta D^1/2 H D^1/2.
1258 const double unstable =
1259 -Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd>(
1260 diffusion_root.asDiagonal() * saddle_hessian *
1261 diffusion_root.asDiagonal(),
1262 Eigen::EigenvaluesOnly)
1263 .eigenvalues()[0];
1264 const SignedLogDet reactant_det = choleskyLogDet(reactant_hessian);
1265 const SignedLogDet saddle_det = luLogDet(saddle_hessian);
1266 if (reactant_det.sign != 1 || saddle_det.sign != -1) {
1267 throw std::runtime_error(
1268 "free-energy Hessian determinant sign disagrees with its "
1269 "inertia");
1270 }
1271 const double determinant_ratio =
1272 std::exp(reactant_det.log_abs - saddle_det.log_abs);
1273 const double prefactor =
1274 config.beta * unstable / two_pi * std::sqrt(determinant_ratio);
1275 const double rate = prefactor * std::exp(-config.beta * barrier);
1276 if (!std::isfinite(prefactor) || !std::isfinite(rate)) continue;
1277 barriers.push_back(barrier);
1278 prefactors.push_back(prefactor);
1279 rates.push_back(rate);
1280 }
1281 const int accepted = static_cast<int>(rates.size());
1282 if (accepted < 2 || 10LL * accepted < 9LL * static_cast<long long>(
1283 config.posterior_samples)) {
1284 throw FreeEnergyRateUnsupportedError(
1285 "fewer than 90% of posterior draws have a minimum at the reactant, "
1286 "an index-one saddle and a positive barrier");
1287 }
1288 const double tail = 0.5 * (1.0 - config.credible_mass);
1289 KramersRateSummary summary;
1290 summary.saddle = saddle;
1291 summary.saddle_gradient_norm = gradient_norm;
1292 meanAndStd(barriers, summary.barrier_mean, summary.barrier_std);
1293 summary.barrier_lower = quantile(barriers, tail);
1294 summary.barrier_upper = quantile(barriers, 1.0 - tail);
1295 meanAndStd(prefactors, summary.prefactor_mean, summary.prefactor_std);
1296 meanAndStd(rates, summary.rate_mean, summary.rate_std);
1297 summary.rate_lower = quantile(rates, tail);
1298 summary.rate_upper = quantile(rates, 1.0 - tail);
1299 summary.samples_requested = config.posterior_samples;
1300 summary.samples_accepted = accepted;
1301 return summary;
1302}
FreeEnergyPathPosterior pathPosterior(const Eigen::MatrixXd &path) const
void fillStandardNormal(SplitMix64 &generator, Eigen::VectorXd &normal)
Independent standard normals, two per pair of uniforms (Box-Muller).
Definition SplitMix64.h:47
Rates rates(const Key &key, const Eigen::VectorXd &frequencies)

◆ predict()

void gpr::bo::FreeEnergySurrogate::predict ( const Eigen::MatrixXd & queries,
Eigen::VectorXd & value,
Eigen::MatrixXd * gradient,
Eigen::VectorXd * variance ) const

Posterior mean of F at each query row; optionally its gradient (n x d) and the latent posterior variance of F.

Definition at line 815 of file FreeEnergySurrogate.cpp.

819{
820 if (!trained_)
821 throw std::logic_error("free-energy surrogate is not trained");
822 if (queries.cols() != dimension_ || queries.rows() == 0) {
823 throw std::invalid_argument("query dimension differs");
824 }
825 requireFinite(queries, "free-energy queries");
826 const std::vector<Functional> rows =
827 trainingFunctionals(points_.rows(), gradient_rows_, dimension_);
828 const Eigen::Index m = queries.rows();
829 const Eigen::Index n = static_cast<Eigen::Index>(rows.size());
830 Eigen::MatrixXd cross(n, m);
831 for (Eigen::Index q = 0; q < m; ++q) {
832 const Eigen::VectorXd query = queries.row(q).transpose();
833 for (Eigen::Index r = 0; r < n; ++r) {
834 const Functional& row = rows[static_cast<std::size_t>(r)];
835 cross(r, q) =
836 priorCovariance(axesOf(row), points_.row(row.point).transpose(),
837 {}, query, lengthscales_, signal_variance_);
838 }
839 }
840 Eigen::VectorXd means =
841 Eigen::VectorXd::Constant(m, prior_mean_) + cross.transpose() * alpha_;
842 Eigen::MatrixXd gradients;
843 if (gradient != nullptr) {
844 const Eigen::VectorXd scale = profileScale(lengthscales_);
845 const derivatives::RadialMeanExpansion expansion = meanExpansion(
846 points_, gradient_rows_, alpha_, scale, signal_variance_);
847 gradients.resize(m, dimension_);
848 for (Eigen::Index q = 0; q < m; ++q) {
849 Eigen::VectorXd descriptor_gradient;
850 const Eigen::VectorXd descriptor =
851 queries.row(q).transpose().cwiseProduct(scale);
854 descriptor, descriptor_gradient)) {
855 throw std::runtime_error(
856 "free-energy mean gradient is not finite");
857 }
858 gradients.row(q) =
859 descriptor_gradient.cwiseProduct(scale).transpose();
860 }
861 }
862 Eigen::VectorXd variances;
863 if (variance != nullptr) {
864 const Eigen::VectorXd explained =
866 variances = (Eigen::VectorXd::Constant(m, signal_variance_) - explained)
867 .cwiseMax(0.0);
868 }
869 value = std::move(means);
870 if (gradient != nullptr) *gradient = std::move(gradients);
871 if (variance != nullptr) *variance = std::move(variances);
872}
bool radialMeanGradient(const RadialMeanExpansion &expansion, MeanDerivativeMethod method, const detail::RealVector< Real > &q, detail::RealVector< Real > &gradient)
Eigen::VectorXd forward_solve_mat_colwise_squared_norm(const EigenMatrix &L, const EigenMatrix &B)
Forward triangular solve followed by columnwise squared norms.
double variance(const Weights &w, const Matrix &covariance)

◆ priorCovariance()

double gpr::bo::FreeEnergySurrogate::priorCovariance ( const std::vector< int > & left_axes,
const Eigen::VectorXd & x,
const std::vector< int > & right_axes,
const Eigen::VectorXd & y,
const Eigen::VectorXd & lengthscales,
double signal_variance )
staticnodiscard

Prior covariance between a derivative of F at x and one at y. Each axis list holds zero, one or two coordinate indices: the value, a gradient component or a Hessian entry.

Definition at line 415 of file FreeEnergySurrogate.cpp.

421{
422 if (x.size() == 0 || x.size() != y.size() ||
423 lengthscales.size() != x.size()) {
424 throw std::invalid_argument("covariance operands differ in dimension");
425 }
426 if (left_axes.size() > 2 || right_axes.size() > 2) {
427 throw std::invalid_argument(
428 "a covariance operand has at most two derivative axes");
429 }
430 for (const auto* axes: {&left_axes, &right_axes}) {
431 for (const int axis: *axes) {
432 if (axis < 0 || axis >= x.size()) {
433 throw std::invalid_argument("derivative axis out of range");
434 }
435 }
436 }
437 return signal_variance * unitCovariance(directionsOf(left_axes, right_axes),
438 x, y, profileScale(lengthscales));
439}
@ x
Definition Enums.h:28
const Eigen::VectorXd & lengthscales() const noexcept

◆ priorMean()

double gpr::bo::FreeEnergySurrogate::priorMean ( ) const
inlinenodiscardnoexcept

Definition at line 258 of file FreeEnergySurrogate.h.

259 {
260 return prior_mean_;
261 }

◆ signalVariance()

double gpr::bo::FreeEnergySurrogate::signalVariance ( ) const
inlinenodiscardnoexcept

Definition at line 254 of file FreeEnergySurrogate.h.

255 {
256 return signal_variance_;
257 }

◆ train()

void gpr::bo::FreeEnergySurrogate::train ( const FreeEnergyObservations & observations)

Replace the training data and refit. On an exception the previous posterior is kept.

Definition at line 680 of file FreeEnergySurrogate.cpp.

681{
682 TrainingSet set = buildTrainingSet(observations, config_, dimension_);
683 Design& design = set.design;
684 std::vector<int>& gradient_rows = set.gradient_rows;
685 const double prior_mean = set.prior_mean;
686 FitStart start = fitStart(observations, set, config_, dimension_);
687 Eigen::VectorXd& w = start.log_hyperparameters;
688 const Eigen::VectorXd& initial_lengthscales = start.initial_lengthscales;
689 const funcmin::MapObjectiveConfig& map = start.map;
690 const int parameter_count = static_cast<int>(w.size());
691
692 FreeEnergyFitReport report;
693 MarginalLikelihoodObjective objective(design, dimension_);
694 if (config_.max_iter > 0) {
695 gpr::ScgOptimizationSettings settings;
696 settings.common.max_iter = static_cast<gpr::Index_t>(config_.max_iter);
697 settings.common.tolerance_func = config_.tol_func;
698 settings.common.tolerance_sol = config_.tol_sol;
699 settings.common.report_level =
700 static_cast<std::uint8_t>(config_.report_level);
702 funcmin::RgminScg optimizer;
703 optimizer.setAlgorithmSettings(settings);
704 const EigenMatrix unused_inputs = design.points;
705 optimizer.optimize(unused_inputs, Eigen::VectorXd{}, design.targets, w,
706 &MarginalLikelihoodObjective::evaluate, objective,
707 map.barrier_strength, initial_lengthscales, &map);
708 if (!w.allFinite()) {
709 throw FreeEnergyInferenceError(
710 "free-energy hyperparameter optimization diverged");
711 }
712 report.iterations = optimizer.completedIterations;
713 report.stop_reason = optimizer.exhaustedIterationBudget ? "budget"
714 : optimizer.failedOptim ? "numerical"
715 : "library";
716 } else {
717 report.stop_reason = "fixed";
718 }
719
720 double fitted_energy = 0.0;
721 {
722 Eigen::VectorXd unused_gradient;
723 gpr::EnergyAndGradient result(fitted_energy, unused_gradient);
724 objective.evaluate(w, EigenMatrix{}, Eigen::VectorXd{},
725 Eigen::VectorXd{}, result);
726 }
727 const double fitted_signal = std::exp(w[0]);
728 double fitted_objective = fitted_energy;
729 if (config_.max_iter > 0) {
730 funcmin::applyMapPenalty(w, map, fitted_objective, nullptr);
731 }
732 const Eigen::VectorXd fitted_lengthscales = expandLengthscales(
733 w.tail(parameter_count - 1).array().exp(), dimension_);
734 EigenMatrix covariance =
735 fitted_signal *
736 unitTrainingCovariance(design, profileScale(fitted_lengthscales));
737 covariance.diagonal() += design.noise;
738 EigenMatrix factor;
739 if (!std::isfinite(fitted_energy) ||
740 !gpr::linalg::cholesky(covariance, factor)) {
741 throw FreeEnergyCholeskyError(
742 "free-energy training covariance does not factor at the fitted "
743 "hyperparameters");
744 }
745 if (!std::isfinite(fitted_objective)) {
746 throw FreeEnergyInferenceError(
747 "free-energy hyperparameters ended outside the prior barrier");
748 }
749 report.objective = fitted_objective;
750 report.negative_log_marginal_likelihood = fitted_energy;
751 Eigen::VectorXd alpha = gpr::linalg::back_solve(
752 factor, gpr::linalg::forward_solve(factor, design.targets));
753 Eigen::VectorXd lengthscales = fitted_lengthscales;
754
755 // Every step that can throw is above; the moves below do not, so a
756 // failed train leaves the previous posterior untouched.
757 points_ = std::move(design.points);
758 gradient_rows_ = std::move(gradient_rows);
759 lengthscales_ = std::move(lengthscales);
760 signal_variance_ = fitted_signal;
761 prior_mean_ = prior_mean;
762 gradient_noise_variance_ = std::move(set.gradient_added);
763 alpha_ = std::move(alpha);
764 factor_ = std::move(factor);
765 fit_report_ = std::move(report);
766 trained_ = true;
767}
bool exhaustedIterationBudget
Definition RgminScg.h:32
int completedIterations
Definition RgminScg.h:33
void optimize(const gpr::EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, Eigen::VectorXd &w, FuncName func_to_min, ClassName &holder, double, const Eigen::VectorXd &lengthscale_rho0=Eigen::VectorXd(), const MapObjectiveConfig *objective_config=nullptr)
Definition RgminScg.inl:16
void setAlgorithmSettings(const gpr::ScgOptimizationSettings &s)
Definition RgminScg.h:38
Eigen::VectorXd forward_solve(const EigenMatrix &L, const Eigen::VectorXd &b)
Forward triangular solve with vector RHS (BLAS equivalent: dtrsv).
Eigen::VectorXd back_solve(const EigenMatrix &L, const Eigen::VectorXd &b)
Back triangular solve with vector RHS (BLAS equivalent: dtrsv).
bool cholesky(const EigenMatrix &C, EigenMatrix &L)
Cholesky decomposition (LAPACK equivalent: dpotrf).
uint32_t Index_t
Definition Macros.h:17
double barrier_strength
Already capped with min(current_barrier_strength, 0.5) by the caller.
OptimizerCommonSettings common
Definition Structures.h:247
ScgCurvatureMode curvature_mode
Definition Structures.h:252

◆ trained()

bool gpr::bo::FreeEnergySurrogate::trained ( ) const
inlinenodiscardnoexcept

Definition at line 179 of file FreeEnergySurrogate.h.

180 {
181 return trained_;
182 }

The documentation for this class was generated from the following files: