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

Namespaces

namespace  testing

Classes

struct  BayesianQuadratureCalibration
class  BayesianQuadratureCholeskyError
struct  BayesianQuadratureConfig
struct  BayesianQuadratureCumulative
struct  BayesianQuadratureFitReport
class  BayesianQuadratureInferenceError
struct  BayesianQuadratureIntegral
struct  BayesianQuadratureIntegralReport
struct  BayesianQuadratureMeasure
class  BayesianQuadratureModel
class  BayesianQuadratureNumericalError
struct  BayesianQuadratureSelection
class  FreeEnergyCholeskyError
 The training covariance did not factor at the fitted hyperparameters. More...
struct  FreeEnergyFitReport
 Last hyperparameter fit. More...
class  FreeEnergyInferenceError
 Hyperparameter inference produced no usable posterior. More...
struct  FreeEnergyObservations
struct  FreeEnergyPathPosterior
class  FreeEnergyRateUnsupportedError
class  FreeEnergySaddleNotFoundError
class  FreeEnergySurrogate
struct  FreeEnergySurrogateConfig
struct  KramersRateConfig
struct  KramersRateSummary
class  Matern32
 Matern 3/2 of the Euclidean radius, k(0) = variance. More...
class  Matern52
 Matern 5/2 of the Euclidean radius, k(0) = variance. More...
struct  MaternMixture
struct  ParameterBound
 One axis of the search box. More...
struct  ParameterObservation
 One evaluated parameter vector, as ParameterSearch::observe() takes it. More...
class  ParameterSearch
 Ask-and-tell minimization of a noisy loss over a parameter box. More...
struct  ParameterSearchConfig
struct  ParameterSearchResult
class  ProductRadial
 f * g on one squared distance. More...
class  RadialShape
 One of SquaredExponential, Matern32 and Matern52 behind a tag. More...
struct  ScalarFitBounds
 Box of the fit in natural units. An empty vector or a non-positive scalar selects the default of defaultScalarFitBounds(). More...
struct  ScalarFitConfig
 Settings of fitScalarHyperparameters(). More...
struct  ScalarFitResult
 Result of fitScalarHyperparameters(). More...
class  ScalarGaussianProcess
 Kernel::covariance(left, right) is the prior covariance of two rows. More...
struct  ScalarHyperparameters
 Hyperparameters of a stationary scalar GP. More...
struct  ScalarLikelihoodData
 Observations the marginal likelihood is evaluated on. More...
class  ScalarSurrogate
 Scalar GP on a parameter vector for a noisy oracle. More...
class  ScaledEuclideanDistance
 Squared Euclidean distance with one length scale, or one per coordinate. More...
class  ScaledRadial
 c * f. The scale is finite and may be negative. The leaf keeps its variance. More...
class  SplitMix64
class  SquaredExponential
 k(r^2) = variance * exp(-r^2 / 2). The value at zero is the variance. More...
class  StationaryKernel
 Covariance k(d(x, x')). Distance::squared and Radial::operator()(double). More...
class  SumRadial
 f + g on one squared distance. More...

Concepts

concept  SquaredDistance
 squared(left, right) is the squared separation of two parameter rows.
concept  RadialFunction
 operator()(double) is the covariance of one squared distance.

Typedefs

using MeanBasis
 Basis functions phi(x) of the parametric mean. The returned vector has the same length at every x.
template<typename Inner>
using Dual

Enumerations

enum class  BayesianQuadratureKernel {
  SquaredExponential , Matern32Product , Matern52Product , Matern32Isotropic ,
  Matern52Isotropic
}
enum class  BayesianQuadratureHyperMode {
  Fixed , MarginalLikelihood , Map , TpMarginal ,
  Marginalized
}
enum class  BayesianQuadratureBasis { FollowConfig = -1 , None = 0 , Constant = 1 , Affine = 2 }
enum class  BayesianQuadratureMeasureKind { LebesgueBox , UniformBox , Gaussian }
enum class  ParameterAcquisition { ExpectedImprovement , LowerConfidenceBound }
enum class  MeanBasisKind { None , Constant , Affine }
 Built-in mean bases of ScalarSurrogate. More...
enum class  RadialKind { SquaredExponential , Matern32 , Matern52 }
 Radial shape of a stationary kernel, selected at run time. More...

Functions

double squaredExponentialBoxMean (const Eigen::VectorXd &point, const Eigen::VectorXd &lower, const Eigen::VectorXd &upper, const Eigen::VectorXd &lengthscales)
double squaredExponentialBoxDouble (const Eigen::VectorXd &lower, const Eigen::VectorXd &upper, const Eigen::VectorXd &lengthscales)
double squaredExponentialBoxCross (const Eigen::VectorXd &lower, const Eigen::VectorXd &first_upper, const Eigen::VectorXd &second_upper, const Eigen::VectorXd &lengthscales)
double maternMixtureUnit (double squared_distance, double nu, const Eigen::VectorXd &nodes, const Eigen::VectorXd &weights)
double analyticUnitMatern (double squared_distance, double nu)
void gaussLegendreInterval (int order, std::vector< double > &nodes, std::vector< double > &weights)
MaternMixture maternMixture (double nu)
const MaternMixture & matern32Mixture ()
const MaternMixture & matern52Mixture ()
double mixtureScale (double node, double nu)
double maternMixtureBoxMean (const MaternMixture &rule, const Eigen::VectorXd &point, const Eigen::VectorXd &lower, const Eigen::VectorXd &upper, const Eigen::VectorXd &lengthscales)
double maternMixtureBoxDouble (const MaternMixture &rule, const Eigen::VectorXd &lower, const Eigen::VectorXd &upper, const Eigen::VectorXd &lengthscales)
double maternMixtureBoxCross (const MaternMixture &rule, const Eigen::VectorXd &lower, const Eigen::VectorXd &first_upper, const Eigen::VectorXd &second_upper, const Eigen::VectorXd &lengthscales)
void requireSymmetricCovariance (const Eigen::MatrixXd &covariance)
double squaredExponentialGaussianMean (const Eigen::VectorXd &point, const Eigen::VectorXd &mean, const Eigen::MatrixXd &covariance, const Eigen::VectorXd &lengthscales)
double squaredExponentialGaussianDouble (const Eigen::MatrixXd &covariance, const Eigen::VectorXd &lengthscales)
double squaredExponentialGaussian1D (double point, double mean, double variance, double lengthscale)
double squaredExponentialGaussianDouble1D (double variance, double lengthscale)
std::vector< Eigen::Index > activeMixtureNodes (const MaternMixture &rule)
void requireProductMixtureBudget (const MaternMixture &rule, Eigen::Index dimension)
template<class Visitor>
void forEachProductMixtureNode (const MaternMixture &rule, const std::vector< Eigen::Index > &active, Eigen::Index dimension, Visitor &&visit)
Eigen::VectorXd maternProductGaussianMeans (const MaternMixture &rule, const Eigen::MatrixXd &points, const Eigen::VectorXd &mean, const Eigen::MatrixXd &covariance, const Eigen::VectorXd &lengthscales)
double maternProductGaussianDouble (const MaternMixture &rule, const Eigen::MatrixXd &covariance, const Eigen::VectorXd &lengthscales)
bool covarianceIsDiagonal (const Eigen::MatrixXd &covariance)
double expectedImprovementScore (double mu, double mu_best, double sigma)
 Jones expected improvement for a maximizer.
double expectedImprovementForMinimum (double mu, double best, double sigma)
 Expected improvement for a minimizer.
double probabilityOfFeasibility (double mu, double sigma, double threshold=0.0)
 Probability that a normal constraint value is feasible.
double constrainedExpectedImprovementForMinimum (double mu, double best, double sigma, double constraint_mu, double constraint_sigma)
 Constrained expected improvement for a minimizer.
double lowerConfidenceBound (double mu, double sigma, double kappa)
 Lower confidence bound for a minimizer, mu - kappa * sigma.
Eigen::VectorXd freeEnergyNoiseFromWeights (const Eigen::VectorXd &weights, double reference_variance, double min_relative_weight)
bool isDiscrete (const ParameterBound &bound)
 True for an integer axis or an axis with allowed values.
void validateBound (const ParameterBound &bound)
 Throw std::invalid_argument unless the axis is well formed.
double unitToParameter (double unit, const ParameterBound &bound)
 Map a unit-cube coordinate to the parameter of its axis.
double parameterToUnit (double parameter, const ParameterBound &bound)
 Unit-cube coordinate of a parameter, the inverse of unitToParameter().
double snapUnit (double unit, const ParameterBound &bound)
 The unit-cube coordinate of the lattice point a coordinate rounds to. A continuous axis returns the clamped coordinate.
template<typename Objective, typename Kernel>
ParameterSearchResult minimize (Objective &&objective, const std::vector< ParameterBound > &bounds, const ParameterSearchConfig &config, const Kernel &kernel)
template<typename Objective>
ParameterSearchResult minimize (Objective &&objective, const std::vector< ParameterBound > &bounds, const ParameterSearchConfig &config)
ScalarFitBounds defaultScalarFitBounds (const ScalarLikelihoodData &data)
 Default box of the fit, from the spread of the observations.
ScalarFitResult fitScalarHyperparameters (const ScalarLikelihoodData &data, const ScalarHyperparameters &initial, const ScalarFitConfig &config={})
 Maximize the log marginal likelihood over the hyperparameters.
Eigen::Index scalarParameterCount (const ScalarLikelihoodData &data)
 Number of fitted parameters: the length scales, the signal variance and, without per-row variances, the noise variance.
double scalarLogMarginalLikelihood (const ScalarLikelihoodData &data, const ScalarHyperparameters &hyper, Eigen::VectorXd *gradient=nullptr)
 Log marginal likelihood log p(y | X, theta) and its gradient.
void fillStandardNormal (SplitMix64 &generator, Eigen::VectorXd &normal)
 Independent standard normals, two per pair of uniforms (Box-Muller).
double kernelMean1D (const SquaredExponential &radial, double point, double lower, double upper, double lengthscale)
double kernelMean1D (const Matern32 &radial, double point, double lower, double upper, double lengthscale)
double kernelMean1D (const Matern52 &radial, double point, double lower, double upper, double lengthscale)
double kernelDoubleIntegral1D (const SquaredExponential &radial, double lower, double upper, double lengthscale)
double kernelDoubleIntegral1D (const Matern32 &radial, double lower, double upper, double lengthscale)
double kernelDoubleIntegral1D (const Matern52 &radial, double lower, double upper, double lengthscale)
template<class Radial>
double kernelMean1DLogLengthDerivative (const Radial &radial, double point, double lower, double upper, double lengthscale)
template<class Radial>
double kernelDoubleIntegral1DLogLengthDerivative (const Radial &radial, double lower, double upper, double lengthscale)
template<typename Radial>
ScaledRadial< Radial > scaledRadial (double scale, Radial radial)
template<typename Left, typename Right>
SumRadial< Left, Right > sumRadial (Left left, Right right)
template<typename Left, typename Right>
ProductRadial< Left, Right > productRadial (Left left, Right right)
template<typename Distance, typename Radial>
requires SquaredDistance<Distance> && RadialFunction<Radial>
StationaryKernel< Distance, Radial > stationaryKernel (Distance distance, Radial radial)
template<typename T, typename Value>
T lift (const Value &value)

Variables

constexpr double kMaxProductMixtureNodes = 2.0e5

Typedef Documentation

◆ Dual

template<typename Inner>
using gpr::derivatives::detail::Dual

Definition at line 241 of file RadialMeanDerivatives.h.

◆ MeanBasis

Initial value:
std::function<Eigen::VectorXd(const Eigen::Ref<const Eigen::VectorXd>&)>

Basis functions phi(x) of the parametric mean. The returned vector has the same length at every x.

Definition at line 37 of file ScalarGaussianProcess.h.

Enumeration Type Documentation

◆ BayesianQuadratureBasis

Basis of the flat-prior Bayes–Sard mean model. It sets the posterior mean and variance, the integral moments, the acquisition scores, the leave-one-out calibration, and the amplitude profile and evidence of the hyperparameter fit. FollowConfig keeps the v1 switch use_prior_mean: true is the constant basis, false is none.

Enumerator
FollowConfig 
None 
Constant 
Affine 

Definition at line 70 of file BayesianQuadrature.h.

◆ BayesianQuadratureHyperMode

◆ BayesianQuadratureKernel

Enumerator
SquaredExponential 
Matern32Product 
Matern52Product 
Matern32Isotropic 
Matern52Isotropic 

Definition at line 49 of file BayesianQuadrature.h.

◆ BayesianQuadratureMeasureKind

◆ MeanBasisKind

enum class gpr::bo::MeanBasisKind
strong

Built-in mean bases of ScalarSurrogate.

Enumerator
None 

Zero mean.

Constant 

phi(x) = 1.

Affine 

phi(x) = (1, x_1, ..., x_d).

Definition at line 34 of file ScalarSurrogate.h.

34 {
36 None,
40 Affine,
41};

◆ ParameterAcquisition

enum class gpr::bo::ParameterAcquisition
strong
Enumerator
ExpectedImprovement 
LowerConfidenceBound 

Definition at line 66 of file ParameterSearch.h.

◆ RadialKind

enum class gpr::bo::RadialKind
strong

Radial shape of a stationary kernel, selected at run time.

Enumerator
SquaredExponential 
Matern32 
Matern52 

Definition at line 258 of file StationaryKernel.h.

Function Documentation

◆ activeMixtureNodes()

std::vector< Eigen::Index > gpr::bo::activeMixtureNodes ( const MaternMixture & rule)
inline

Indices of the mixture nodes whose weight is above the cut that keeps the pruned mass below the kernel error budget.

Definition at line 375 of file BayesianQuadratureMoments.h.

376{
377 std::vector<Eigen::Index> active;
378 for (Eigen::Index index = 0; index < rule.nodes.size(); ++index) {
379 if (rule.weights[index] > 1e-18) active.push_back(index);
380 }
381 return active;
382}
Eigen::VectorXd nodes
Quadrature nodes t = exp(u) for the gamma measure.

◆ analyticUnitMatern()

double gpr::bo::analyticUnitMatern ( double squared_distance,
double nu )
inline

Definition at line 106 of file BayesianQuadratureMoments.h.

107{
108 return nu == 1.5 ? Matern32()(squared_distance)
109 : Matern52()(squared_distance);
110}
Matern 5/2 of the Euclidean radius, k(0) = variance.

◆ constrainedExpectedImprovementForMinimum()

double gpr::bo::constrainedExpectedImprovementForMinimum ( double mu,
double best,
double sigma,
double constraint_mu,
double constraint_sigma )
inline

Constrained expected improvement for a minimizer.

Expected improvement of the loss times the probability that an independent constraint model is feasible: Gardner et al. (2014) and Gelbart, Snoek and Adams (2014). The constraint is feasible at or below zero.

Definition at line 79 of file ExpectedImprovement.h.

83{
84 return expectedImprovementForMinimum(mu, best, sigma) *
85 probabilityOfFeasibility(constraint_mu, constraint_sigma);
86}
double probabilityOfFeasibility(double mu, double sigma, double threshold=0.0)
Probability that a normal constraint value is feasible.
double expectedImprovementForMinimum(double mu, double best, double sigma)
Expected improvement for a minimizer.

◆ covarianceIsDiagonal()

bool gpr::bo::covarianceIsDiagonal ( const Eigen::MatrixXd & covariance)
inline

Definition at line 481 of file BayesianQuadratureMoments.h.

482{
483 for (Eigen::Index column = 0; column < covariance.cols(); ++column) {
484 for (Eigen::Index row = 0; row < covariance.rows(); ++row) {
485 if (row != column && covariance(row, column) != 0.0) return false;
486 }
487 }
488 return true;
489}

◆ defaultScalarFitBounds()

ScalarFitBounds gpr::bo::defaultScalarFitBounds ( const ScalarLikelihoodData & data)

Default box of the fit, from the spread of the observations.

Length scale of an axis: 0.02 to 20 times the range of that column of x. Signal variance: 1e-4 to 1e3 times the sample variance of y. Noise variance: 1e-8 to 10 times the sample variance of y. A column or a y without spread uses one as its scale.

Definition at line 107 of file ScalarHyperparameterFit.cpp.

108{
109 const Eigen::Index dimension = data.x.cols();
110 if (data.x.rows() == 0 || dimension == 0 ||
111 data.y.size() != data.x.rows()) {
112 throw std::invalid_argument("likelihood observations are invalid");
113 }
114 ScalarFitBounds bounds;
115 bounds.length_scale_lower.resize(dimension);
116 bounds.length_scale_upper.resize(dimension);
117 for (Eigen::Index dim = 0; dim < dimension; ++dim) {
118 double range = data.x.col(dim).maxCoeff() - data.x.col(dim).minCoeff();
119 if (!(range > 0.0) || !std::isfinite(range)) range = 1.0;
120 bounds.length_scale_lower[dim] = 0.02 * range;
121 bounds.length_scale_upper[dim] = 20.0 * range;
122 }
123 const double variance = sampleVariance(data.y);
124 bounds.signal_variance_lower = 1e-4 * variance;
125 bounds.signal_variance_upper = 1e3 * variance;
126 bounds.noise_variance_lower = 1e-8 * variance;
127 bounds.noise_variance_upper = 10.0 * variance;
128 return bounds;
129}
Eigen::MatrixXd x
Row i is the parameter vector of observation i.

◆ expectedImprovementForMinimum()

double gpr::bo::expectedImprovementForMinimum ( double mu,
double best,
double sigma )
inline

Expected improvement for a minimizer.

The maximizer score on negated values. best is the smallest loss seen so far.

Definition at line 46 of file ExpectedImprovement.h.

48{
49 return expectedImprovementScore(-mu, -best, sigma);
50}
double expectedImprovementScore(double mu, double mu_best, double sigma)
Jones expected improvement for a maximizer.

◆ expectedImprovementScore()

double gpr::bo::expectedImprovementScore ( double mu,
double mu_best,
double sigma )
inline

Jones expected improvement for a maximizer.

EI = (mu - mu_best) Phi(z) + sigma phi(z), with z = (mu - mu_best) / sigma. The score is zero when sigma is not positive or the inputs are not finite.

Definition at line 27 of file ExpectedImprovement.h.

28{
29 if (!(sigma > 0.0) || !std::isfinite(sigma) || !std::isfinite(mu) ||
30 !std::isfinite(mu_best)) {
31 return 0.0;
32 }
33 const double z = (mu - mu_best) / sigma;
34 const double phi = std::exp(-0.5 * z * z) / std::sqrt(2.0 * M_PI);
35 const double Phi = 0.5 * std::erfc(-z / std::sqrt(2.0));
36 const double ei = (mu - mu_best) * Phi + sigma * phi;
37 return (std::isfinite(ei) && ei > 0.0) ? ei : 0.0;
38}
@ z
Definition Enums.h:28

◆ fillStandardNormal()

void gpr::bo::fillStandardNormal ( SplitMix64 & generator,
Eigen::VectorXd & normal )
inline

Independent standard normals, two per pair of uniforms (Box-Muller).

Definition at line 47 of file SplitMix64.h.

48{
49 const double two_pi = 2.0 * std::acos(-1.0);
50 for (Eigen::Index index = 0; index < normal.size(); index += 2) {
51 const double radius =
52 std::sqrt(-2.0 * std::log(generator.uniformOpen()));
53 const double angle = two_pi * generator.uniformOpen();
54 normal[index] = radius * std::cos(angle);
55 if (index + 1 < normal.size()) {
56 normal[index + 1] = radius * std::sin(angle);
57 }
58 }
59}
double uniformOpen()
Uniform on the open interval (0, 1).
Definition SplitMix64.h:35

◆ fitScalarHyperparameters()

ScalarFitResult gpr::bo::fitScalarHyperparameters ( const ScalarLikelihoodData & data,
const ScalarHyperparameters & initial,
const ScalarFitConfig & config = {} )

Maximize the log marginal likelihood over the hyperparameters.

Every start runs the rgmin L-BFGS solver on the logarithms of the hyperparameters with the analytic gradient, inside the box. The start with the largest likelihood is returned. A noise variance supplied per row is kept and only the length scales and the signal variance move.

Parameters
initialFirst start, clipped into the box. A single length scale applies to every axis.
Exceptions
std::invalid_argumentfor inconsistent sizes or an empty box.
std::runtime_errorwhen no start has a finite likelihood.

Definition at line 131 of file ScalarHyperparameterFit.cpp.

134{
135 const Eigen::Index dimension = data.x.cols();
136 const bool shared_noise = data.noise_variances.size() == 0;
137 if (config.starts <= 0 || config.max_iterations <= 0 ||
138 !(config.tolerance > 0.0) || !std::isfinite(config.tolerance)) {
139 throw std::invalid_argument("hyperparameter fit config is invalid");
140 }
141 ScalarHyperparameters first = initial;
142 if (first.length_scales.size() == 1 && dimension > 1) {
143 first.length_scales =
144 Eigen::VectorXd::Constant(dimension, initial.length_scales[0]);
145 }
146 if (!shared_noise) first.noise_variance = 0.0;
147 detail::requireLikelihoodInputs(data, first);
148
149 const ScalarFitBounds defaults = defaultScalarFitBounds(data);
150 ScalarFitBounds box = config.bounds;
151 if (box.length_scale_lower.size() == 0) {
152 box.length_scale_lower = defaults.length_scale_lower;
153 }
154 if (box.length_scale_upper.size() == 0) {
155 box.length_scale_upper = defaults.length_scale_upper;
156 }
157 if (box.length_scale_lower.size() == 1 && dimension > 1) {
158 box.length_scale_lower = Eigen::VectorXd::Constant(
159 dimension, config.bounds.length_scale_lower[0]);
160 }
161 if (box.length_scale_upper.size() == 1 && dimension > 1) {
162 box.length_scale_upper = Eigen::VectorXd::Constant(
163 dimension, config.bounds.length_scale_upper[0]);
164 }
165 if (box.length_scale_lower.size() != dimension ||
166 box.length_scale_upper.size() != dimension) {
167 throw std::invalid_argument("length scale bounds do not match");
168 }
169 if (!(box.signal_variance_lower > 0.0)) {
170 box.signal_variance_lower = defaults.signal_variance_lower;
171 }
172 if (!(box.signal_variance_upper > 0.0)) {
173 box.signal_variance_upper = defaults.signal_variance_upper;
174 }
175 if (!(box.noise_variance_lower > 0.0)) {
176 box.noise_variance_lower = defaults.noise_variance_lower;
177 }
178 if (!(box.noise_variance_upper > 0.0)) {
179 box.noise_variance_upper = defaults.noise_variance_upper;
180 }
181
182 const Eigen::Index count = scalarParameterCount(data);
183 Eigen::VectorXd lower(count);
184 Eigen::VectorXd upper(count);
185 for (Eigen::Index dim = 0; dim < dimension; ++dim) {
186 requirePositiveInterval(box.length_scale_lower[dim],
187 box.length_scale_upper[dim],
188 "length scale bounds are invalid");
189 lower[dim] = std::log(box.length_scale_lower[dim]);
190 upper[dim] = std::log(box.length_scale_upper[dim]);
191 }
192 requirePositiveInterval(box.signal_variance_lower,
193 box.signal_variance_upper,
194 "signal variance bounds are invalid");
195 lower[dimension] = std::log(box.signal_variance_lower);
196 upper[dimension] = std::log(box.signal_variance_upper);
197 if (shared_noise) {
198 requirePositiveInterval(box.noise_variance_lower,
199 box.noise_variance_upper,
200 "noise variance bounds are invalid");
201 lower[dimension + 1] = std::log(box.noise_variance_lower);
202 upper[dimension + 1] = std::log(box.noise_variance_upper);
203 }
204
205 Eigen::VectorXd start(count);
206 start.head(dimension) = first.length_scales.array().log();
207 start[dimension] = std::log(first.signal_variance);
208 if (shared_noise) {
209 start[dimension + 1] = first.noise_variance > 0.0
210 ? std::log(first.noise_variance)
211 : -std::numeric_limits<double>::infinity();
212 }
213 start = start.cwiseMax(lower).cwiseMin(upper);
214
215 gpr::ScgOptimizationSettings settings;
216 settings.common.max_iter = static_cast<Index_t>(config.max_iterations);
217 settings.common.tolerance_func = config.tolerance;
218 settings.common.tolerance_sol = config.tolerance;
219 settings.common.report_level = 0;
220 funcmin::MapObjectiveConfig objective_config;
221 objective_config.prior_weight = Eigen::VectorXd::Zero(count);
222 objective_config.parameter_lower = lower;
223 objective_config.parameter_upper = upper;
224
225 NegativeLogLikelihood objective(data);
226 SplitMix64 generator(config.seed);
227 ScalarFitResult result;
228 Eigen::VectorXd best;
229 double best_value = std::numeric_limits<double>::infinity();
230 for (int index = 0; index < config.starts; ++index) {
231 Eigen::VectorXd parameters = start;
232 if (index > 0) {
233 for (Eigen::Index k = 0; k < count; ++k) {
234 parameters[k] =
235 lower[k] + generator.uniformOpen() * (upper[k] - lower[k]);
236 }
237 }
238 ++result.starts;
239 if (!std::isfinite(objective.value(parameters, nullptr))) continue;
240 funcmin::RgminOpt optimizer;
241 optimizer.setMethod(RGMIN_LBFGS);
242 // One unit is a factor e in a length scale or a variance.
243 optimizer.setInitialLogMove(1.0);
244 optimizer.setAlgorithmSettings(settings);
245 Eigen::VectorXd trial = parameters;
246 optimizer.optimize(data.x, Eigen::VectorXd{}, data.y, trial,
247 &NegativeLogLikelihood::evaluate, objective, 0.0,
248 Eigen::VectorXd{}, &objective_config);
249 if (!optimizer.failedOptim) ++result.converged_starts;
250 if (trial.allFinite()) {
251 trial = trial.cwiseMax(lower).cwiseMin(upper);
252 } else {
253 trial = parameters;
254 }
255 // A run that stops early still leaves its last accepted point; it
256 // counts when it improves on the start.
257 for (const Eigen::VectorXd& candidate: {parameters, trial}) {
258 const double value = objective.value(candidate, nullptr);
259 if (value < best_value) {
260 best_value = value;
261 best = candidate;
262 }
263 }
264 }
265 result.evaluations = objective.evaluations;
266 if (!std::isfinite(best_value)) {
267 throw std::runtime_error(
268 "no start of the hyperparameter fit has a finite likelihood");
269 }
270 result.hyperparameters = fromLogParameters(data, best);
271 result.log_marginal_likelihood = -best_value;
272 return result;
273}
void setAlgorithmSettings(const gpr::ScgOptimizationSettings &s)
Definition RgminOpt.h:44
void setMethod(rgmin::Method m) noexcept
Definition RgminOpt.h:49
void setInitialLogMove(double distance) noexcept
Definition RgminOpt.h:167
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 RgminOpt.inl:19
ScalarFitBounds defaultScalarFitBounds(const ScalarLikelihoodData &data)
Default box of the fit, from the spread of the observations.
Eigen::Index scalarParameterCount(const ScalarLikelihoodData &data)
Number of fitted parameters: the length scales, the signal variance and, without per-row variances,...
uint32_t Index_t
Definition Macros.h:17
Eigen::VectorXd prior_weight
Eigen::VectorXd parameter_lower
Eigen::VectorXd parameter_upper
OptimizerCommonSettings common
Definition Structures.h:247
double tolerance
Gradient-norm tolerance of the L-BFGS runs.
Result of fitScalarHyperparameters().
Eigen::VectorXd length_scales
One length scale per axis.

◆ forEachProductMixtureNode()

template<class Visitor>
void gpr::bo::forEachProductMixtureNode ( const MaternMixture & rule,
const std::vector< Eigen::Index > & active,
Eigen::Index dimension,
Visitor && visit )
inline

Visits every joint node of a product mixture. visit(weight, scales) receives the product weight and the per-axis scale factors.

Definition at line 405 of file BayesianQuadratureMoments.h.

408{
409 std::vector<std::size_t> counter(static_cast<std::size_t>(dimension), 0);
410 Eigen::VectorXd scales(dimension);
411 while (true) {
412 long double weight = 1.0L;
413 for (Eigen::Index dim = 0; dim < dimension; ++dim) {
414 const Eigen::Index node =
415 active[counter[static_cast<std::size_t>(dim)]];
416 weight *= rule.weights[node];
417 scales[dim] = mixtureScale(rule.nodes[node], rule.nu);
418 }
419 visit(static_cast<double>(weight), scales);
420 Eigen::Index axis = 0;
421 while (axis < dimension) {
422 auto& slot = counter[static_cast<std::size_t>(axis)];
423 if (++slot < active.size()) break;
424 slot = 0;
425 ++axis;
426 }
427 if (axis == dimension) return;
428 }
429}
double mixtureScale(double node, double nu)

◆ freeEnergyNoiseFromWeights()

Eigen::VectorXd gpr::bo::freeEnergyNoiseFromWeights ( const Eigen::VectorXd & weights,
double reference_variance,
double min_relative_weight )

noise[i] = reference * max(w) / max(w[i], min_relative * max(w)). Scale-invariant in the weights. Every weight is positive and finite, reference is positive and finite, and min_relative lies in (0, 1]. Throws std::domain_error when a noise variance overflows.

Definition at line 344 of file FreeEnergySurrogate.cpp.

347{
348 if (weights.size() == 0) {
349 throw std::invalid_argument("weights are empty");
350 }
351 if (!weights.allFinite() || (weights.array() <= 0.0).any()) {
352 throw std::invalid_argument("weights must be positive and finite");
353 }
354 if (!(reference_variance > 0.0) || !std::isfinite(reference_variance)) {
355 throw std::invalid_argument(
356 "reference variance must be positive and finite");
357 }
358 if (!(min_relative_weight > 0.0) || !(min_relative_weight <= 1.0)) {
359 throw std::invalid_argument(
360 "minimum relative weight must be in (0, 1]");
361 }
362 const double largest = weights.maxCoeff();
363 const double floor = min_relative_weight * largest;
364 Eigen::VectorXd noise(weights.size());
365 for (Eigen::Index i = 0; i < weights.size(); ++i) {
366 // The ratio lies in [1, 1 / min_relative_weight]; reference * largest
367 // would overflow for large weights before the division.
368 const double ratio = largest / std::max(weights[i], floor);
369 noise[i] = reference_variance * ratio;
370 if (!std::isfinite(noise[i])) {
371 throw std::domain_error(
372 "noise variance from weights overflows; lower the reference "
373 "variance or raise the minimum relative weight");
374 }
375 }
376 return noise;
377}

◆ gaussLegendreInterval()

void gpr::bo::gaussLegendreInterval ( int order,
std::vector< double > & nodes,
std::vector< double > & weights )
inline

Definition at line 112 of file BayesianQuadratureMoments.h.

114{
115 nodes.resize(static_cast<std::size_t>(order));
116 weights.resize(static_cast<std::size_t>(order));
117 const double pi = std::acos(-1.0);
118 for (int index = 0; index < (order + 1) / 2; ++index) {
119 double root =
120 std::cos(pi * (index + 0.75) / (static_cast<double>(order) + 0.5));
121 for (int iteration = 0; iteration < 40; ++iteration) {
122 double previous = 1.0;
123 double current = root;
124 for (int degree = 2; degree <= order; ++degree) {
125 const double next = ((2.0 * degree - 1.0) * root * current -
126 (degree - 1.0) * previous) /
127 degree;
128 previous = current;
129 current = next;
130 }
131 const double derivative =
132 order * (previous - root * current) / (1.0 - root * root);
133 const double delta = current / derivative;
134 root -= delta;
135 if (std::abs(delta) <=
136 4.0 * std::numeric_limits<double>::epsilon()) {
137 break;
138 }
139 }
140 const int mirror = order - 1 - index;
141 nodes[static_cast<std::size_t>(index)] = -root;
142 nodes[static_cast<std::size_t>(mirror)] = root;
143 double previous = 1.0;
144 double current = root;
145 for (int degree = 2; degree <= order; ++degree) {
146 const double next = ((2.0 * degree - 1.0) * root * current -
147 (degree - 1.0) * previous) /
148 degree;
149 previous = current;
150 current = next;
151 }
152 const double derivative =
153 order * (previous - root * current) / (1.0 - root * root);
154 const double weight =
155 2.0 / ((1.0 - root * root) * derivative * derivative);
156 weights[static_cast<std::size_t>(index)] = weight;
157 weights[static_cast<std::size_t>(mirror)] = weight;
158 }
159}
constexpr std::array< Real, 8 > nodes

◆ isDiscrete()

bool gpr::bo::isDiscrete ( const ParameterBound & bound)
inline

True for an integer axis or an axis with allowed values.

Definition at line 127 of file ParameterSearch.h.

128{
129 return bound.integer || !bound.allowed_values.empty();
130}
std::vector< double > allowed_values

◆ kernelDoubleIntegral1D() [1/3]

double gpr::bo::kernelDoubleIntegral1D ( const Matern32 & radial,
double lower,
double upper,
double lengthscale )
inline

Definition at line 511 of file StationaryKernel.h.

513{
514 detail::requireIntegralBounds(lower, upper, lengthscale);
515 const double scaled = std::sqrt(3.0) * (upper - lower) / lengthscale;
516 const double threshold =
517 std::pow(30240.0 * std::numeric_limits<double>::epsilon(), 1.0 / 7.0);
518 double unit = 0.0;
519 if (scaled < threshold) {
520 const double squared = scaled * scaled;
521 unit = squared *
522 (1.0 / 3.0 +
523 squared * (-1.0 / 36.0 +
524 scaled * (1.0 / 90.0 +
525 scaled * (-1.0 / 360.0 +
526 scaled * (1.0 / 1890.0 -
527 scaled / 12096.0)))));
528 } else {
529 unit =
530 (2.0 / 3.0) * (3.0 * scaled + (scaled + 3.0) * std::expm1(-scaled));
531 }
532 return radial.variance() * lengthscale * lengthscale * unit;
533}
double variance() const noexcept

◆ kernelDoubleIntegral1D() [2/3]

double gpr::bo::kernelDoubleIntegral1D ( const Matern52 & radial,
double lower,
double upper,
double lengthscale )
inline

Definition at line 535 of file StationaryKernel.h.

537{
538 detail::requireIntegralBounds(lower, upper, lengthscale);
539 const double scaled = std::sqrt(5.0) * (upper - lower) / lengthscale;
540 const double threshold =
541 std::pow(22680.0 * std::numeric_limits<double>::epsilon(), 1.0 / 7.0);
542 double unit = 0.0;
543 if (scaled < threshold) {
544 const double squared = scaled * scaled;
545 unit =
546 squared *
547 (1.0 / 5.0 +
548 squared * (-1.0 / 180.0 +
549 squared * (1.0 / 1800.0 +
550 scaled * (-1.0 / 4725.0 +
551 scaled * (1.0 / 20160.0 -
552 scaled / 113400.0)))));
553 } else {
554 unit = (2.0 / 15.0) *
555 (scaled * scaled + 15.0 * scaled +
556 (scaled * scaled + 7.0 * scaled + 15.0) * std::expm1(-scaled));
557 }
558 return radial.variance() * lengthscale * lengthscale * unit;
559}
double variance() const noexcept

◆ kernelDoubleIntegral1D() [3/3]

double gpr::bo::kernelDoubleIntegral1D ( const SquaredExponential & radial,
double lower,
double upper,
double lengthscale )
inline

Definition at line 487 of file StationaryKernel.h.

490{
491 detail::requireIntegralBounds(lower, upper, lengthscale);
492 const double scaled_width = (upper - lower) / lengthscale;
493 const double threshold =
494 std::pow(253440.0 * std::numeric_limits<double>::epsilon(), 1.0 / 10.0);
495 double unit = 0.0;
496 if (scaled_width < threshold) {
497 const double squared = scaled_width * scaled_width;
498 unit = squared *
499 (1.0 + squared * (-1.0 / 12.0 +
500 squared * (1.0 / 120.0 +
501 squared * (-1.0 / 1344.0 +
502 squared / 17280.0))));
503 } else {
504 unit = 2.0 * (scaled_width * std::sqrt(std::acos(-1.0) / 2.0) *
505 numerics::erf(scaled_width / std::sqrt(2.0)) +
506 std::expm1(-0.5 * scaled_width * scaled_width));
507 }
508 return radial.variance() * lengthscale * lengthscale * unit;
509}
double variance() const noexcept
double erf(double x) noexcept

◆ kernelDoubleIntegral1DLogLengthDerivative()

template<class Radial>
double gpr::bo::kernelDoubleIntegral1DLogLengthDerivative ( const Radial & radial,
double lower,
double upper,
double lengthscale )

Definition at line 575 of file StationaryKernel.h.

578{
579 detail::requireIntegralBounds(lower, upper, lengthscale);
580 const double scaled_width = (upper - lower) / lengthscale;
581 const double primitive =
582 kernelMean1D(radial, lower, lower, upper, lengthscale) /
583 (radial.variance() * lengthscale);
584 return 2.0 * (kernelDoubleIntegral1D(radial, lower, upper, lengthscale) -
585 radial.variance() * lengthscale * lengthscale * scaled_width *
586 primitive);
587}
double kernelMean1D(const SquaredExponential &radial, double point, double lower, double upper, double lengthscale)
double kernelDoubleIntegral1D(const SquaredExponential &radial, double lower, double upper, double lengthscale)

◆ kernelMean1D() [1/3]

double gpr::bo::kernelMean1D ( const Matern32 & radial,
double point,
double lower,
double upper,
double lengthscale )
inline

Definition at line 463 of file StationaryKernel.h.

465{
466 detail::requireIntegralBounds(lower, upper, lengthscale);
467 if (!std::isfinite(point)) {
468 throw std::invalid_argument("kernel integral point must be finite");
469 }
470 return radial.variance() * lengthscale *
471 (detail::matern32Primitive((point - lower) / lengthscale) +
472 detail::matern32Primitive((upper - point) / lengthscale));
473}

◆ kernelMean1D() [2/3]

double gpr::bo::kernelMean1D ( const Matern52 & radial,
double point,
double lower,
double upper,
double lengthscale )
inline

Definition at line 475 of file StationaryKernel.h.

477{
478 detail::requireIntegralBounds(lower, upper, lengthscale);
479 if (!std::isfinite(point)) {
480 throw std::invalid_argument("kernel integral point must be finite");
481 }
482 return radial.variance() * lengthscale *
483 (detail::matern52Primitive((point - lower) / lengthscale) +
484 detail::matern52Primitive((upper - point) / lengthscale));
485}

◆ kernelMean1D() [3/3]

double gpr::bo::kernelMean1D ( const SquaredExponential & radial,
double point,
double lower,
double upper,
double lengthscale )
inline

Definition at line 448 of file StationaryKernel.h.

450{
451 detail::requireIntegralBounds(lower, upper, lengthscale);
452 if (!std::isfinite(point)) {
453 throw std::invalid_argument("kernel integral point must be finite");
454 }
455 const double root_two_length = std::sqrt(2.0) * lengthscale;
456 const double alpha = (lower - point) / root_two_length;
457 const double beta = (upper - point) / root_two_length;
458 return radial.variance() * lengthscale * std::sqrt(std::acos(-1.0) / 2.0) *
459 detail::stableErfDifference(alpha, beta,
460 (upper - lower) / root_two_length);
461}

◆ kernelMean1DLogLengthDerivative()

template<class Radial>
double gpr::bo::kernelMean1DLogLengthDerivative ( const Radial & radial,
double point,
double lower,
double upper,
double lengthscale )

Definition at line 562 of file StationaryKernel.h.

565{
566 const double left = (point - lower) / lengthscale;
567 const double right = (upper - point) / lengthscale;
568 return kernelMean1D(radial, point, lower, upper, lengthscale) -
569 radial.variance() * lengthscale *
570 (left * (radial(left * left) / radial.variance()) +
571 right * (radial(right * right) / radial.variance()));
572}

◆ lift()

template<typename T, typename Value>
T gpr::derivatives::lift ( const Value & value)

Definition at line 35 of file NestedAutoDiff.h.

36{
37 return Lift<T>::from(value);
38}

◆ lowerConfidenceBound()

double gpr::bo::lowerConfidenceBound ( double mu,
double sigma,
double kappa )
inline

Lower confidence bound for a minimizer, mu - kappa * sigma.

A non-finite input returns +infinity so a minimizer skips the point.

Definition at line 93 of file ExpectedImprovement.h.

94{
95 if (!(sigma >= 0.0) || !std::isfinite(sigma) || !std::isfinite(mu) ||
96 !(kappa >= 0.0) || !std::isfinite(kappa)) {
97 return std::numeric_limits<double>::infinity();
98 }
99 return mu - kappa * sigma;
100}

◆ matern32Mixture()

const MaternMixture & gpr::bo::matern32Mixture ( )
inline

Definition at line 221 of file BayesianQuadratureMoments.h.

222{
223 static const MaternMixture rule = maternMixture(1.5);
224 return rule;
225}
MaternMixture maternMixture(double nu)

◆ matern52Mixture()

const MaternMixture & gpr::bo::matern52Mixture ( )
inline

Definition at line 227 of file BayesianQuadratureMoments.h.

228{
229 static const MaternMixture rule = maternMixture(2.5);
230 return rule;
231}

◆ maternMixture()

MaternMixture gpr::bo::maternMixture ( double nu)
inline

Plain generalized Gauss–Laguerre at a few hundred nodes leaves a relative kernel error near 5e-5, because exp(-a/t) is not a polynomial in t. The substitution t = exp(u) makes the gamma-mixture integrand smooth, and a fixed Gauss–Legendre panel rule then matches the closed-form Matérn to a small multiple of machine epsilon. The window and panel count are the smallest values in the search below that meet that test.

Definition at line 167 of file BayesianQuadratureMoments.h.

168{
169 constexpr double kLogLower = -24.0;
170 constexpr double kLogUpper = 12.0;
171 constexpr int kLegendreOrder = 32;
172 constexpr int kPanels = 8;
173 const double acceptance = 1024.0 * std::numeric_limits<double>::epsilon();
174 std::vector<double> legendre_nodes;
175 std::vector<double> legendre_weights;
176 gaussLegendreInterval(kLegendreOrder, legendre_nodes, legendre_weights);
177 const double gamma = std::tgamma(nu);
178 const int count = kPanels * kLegendreOrder;
179 MaternMixture rule;
180 rule.nu = nu;
181 rule.nodes.resize(count);
182 rule.weights.resize(count);
183 const double panel_width = (kLogUpper - kLogLower) / kPanels;
184 int slot = 0;
185 for (int panel = 0; panel < kPanels; ++panel) {
186 const double panel_lower = kLogLower + panel * panel_width;
187 const double midpoint = panel_lower + 0.5 * panel_width;
188 for (int index = 0; index < kLegendreOrder; ++index) {
189 const double u =
190 midpoint + 0.5 * panel_width *
191 legendre_nodes[static_cast<std::size_t>(index)];
192 const double jacobian =
193 0.5 * panel_width *
194 legendre_weights[static_cast<std::size_t>(index)];
195 const double t = std::exp(u);
196 const double log_weight = nu * u - t;
197 rule.nodes[slot] = t;
198 rule.weights[slot] = log_weight < -700.0
199 ? 0.0
200 : jacobian * std::exp(log_weight) / gamma;
201 ++slot;
202 }
203 }
204 double error = 0.0;
205 for (int step = 0; step <= 24; ++step) {
206 const double radius = std::ldexp(1.0, step - 8);
207 const double squared = radius * radius;
208 error = std::max(
209 error,
210 std::abs(maternMixtureUnit(squared, nu, rule.nodes, rule.weights) -
211 analyticUnitMatern(squared, nu)));
212 }
213 rule.kernel_abs_error = error;
214 if (error > acceptance) {
215 throw std::runtime_error(
216 "Matern scale mixture did not match the closed form");
217 }
218 return rule;
219}
double maternMixtureUnit(double squared_distance, double nu, const Eigen::VectorXd &nodes, const Eigen::VectorXd &weights)
double analyticUnitMatern(double squared_distance, double nu)
void gaussLegendreInterval(int order, std::vector< double > &nodes, std::vector< double > &weights)
double kernel_abs_error
Max absolute error of the unit kernel on a geometric radius grid.

◆ maternMixtureBoxCross()

double gpr::bo::maternMixtureBoxCross ( const MaternMixture & rule,
const Eigen::VectorXd & lower,
const Eigen::VectorXd & first_upper,
const Eigen::VectorXd & second_upper,
const Eigen::VectorXd & lengthscales )
inline

Definition at line 271 of file BayesianQuadratureMoments.h.

276{
277 long double sum = 0.0L;
278 for (Eigen::Index index = 0; index < rule.nodes.size(); ++index) {
279 if (rule.weights[index] == 0.0) continue;
280 const Eigen::VectorXd scaled =
281 lengthscales * mixtureScale(rule.nodes[index], rule.nu);
282 sum += static_cast<long double>(rule.weights[index]) *
283 squaredExponentialBoxCross(lower, first_upper, second_upper,
284 scaled);
285 }
286 return static_cast<double>(sum);
287}
double squaredExponentialBoxCross(const Eigen::VectorXd &lower, const Eigen::VectorXd &first_upper, const Eigen::VectorXd &second_upper, const Eigen::VectorXd &lengthscales)

◆ maternMixtureBoxDouble()

double gpr::bo::maternMixtureBoxDouble ( const MaternMixture & rule,
const Eigen::VectorXd & lower,
const Eigen::VectorXd & upper,
const Eigen::VectorXd & lengthscales )
inline

Definition at line 255 of file BayesianQuadratureMoments.h.

259{
260 long double sum = 0.0L;
261 for (Eigen::Index index = 0; index < rule.nodes.size(); ++index) {
262 if (rule.weights[index] == 0.0) continue;
263 const Eigen::VectorXd scaled =
264 lengthscales * mixtureScale(rule.nodes[index], rule.nu);
265 sum += static_cast<long double>(rule.weights[index]) *
266 squaredExponentialBoxDouble(lower, upper, scaled);
267 }
268 return static_cast<double>(sum);
269}
double squaredExponentialBoxDouble(const Eigen::VectorXd &lower, const Eigen::VectorXd &upper, const Eigen::VectorXd &lengthscales)

◆ maternMixtureBoxMean()

double gpr::bo::maternMixtureBoxMean ( const MaternMixture & rule,
const Eigen::VectorXd & point,
const Eigen::VectorXd & lower,
const Eigen::VectorXd & upper,
const Eigen::VectorXd & lengthscales )
inline

Definition at line 238 of file BayesianQuadratureMoments.h.

243{
244 long double sum = 0.0L;
245 for (Eigen::Index index = 0; index < rule.nodes.size(); ++index) {
246 if (rule.weights[index] == 0.0) continue;
247 const Eigen::VectorXd scaled =
248 lengthscales * mixtureScale(rule.nodes[index], rule.nu);
249 sum += static_cast<long double>(rule.weights[index]) *
250 squaredExponentialBoxMean(point, lower, upper, scaled);
251 }
252 return static_cast<double>(sum);
253}
double squaredExponentialBoxMean(const Eigen::VectorXd &point, const Eigen::VectorXd &lower, const Eigen::VectorXd &upper, const Eigen::VectorXd &lengthscales)

◆ maternMixtureUnit()

double gpr::bo::maternMixtureUnit ( double squared_distance,
double nu,
const Eigen::VectorXd & nodes,
const Eigen::VectorXd & weights )
inline

Definition at line 92 of file BayesianQuadratureMoments.h.

95{
96 long double sum = 0.0L;
97 for (Eigen::Index index = 0; index < nodes.size(); ++index) {
98 const double node = nodes[index];
99 const double log_factor = -0.5 * squared_distance * nu / node;
100 if (log_factor < -700.0) continue;
101 sum += static_cast<long double>(weights[index]) * std::exp(log_factor);
102 }
103 return static_cast<double>(sum);
104}

◆ maternProductGaussianDouble()

double gpr::bo::maternProductGaussianDouble ( const MaternMixture & rule,
const Eigen::MatrixXd & covariance,
const Eigen::VectorXd & lengthscales )
inline

Definition at line 463 of file BayesianQuadratureMoments.h.

466{
467 const Eigen::Index dimension = lengthscales.size();
468 requireProductMixtureBudget(rule, dimension);
469 const std::vector<Eigen::Index> active = activeMixtureNodes(rule);
470 long double sum = 0.0L;
472 rule, active, dimension,
473 [&](double weight, const Eigen::VectorXd& scales) {
474 sum += static_cast<long double>(weight) *
476 covariance, lengthscales.cwiseProduct(scales));
477 });
478 return static_cast<double>(sum);
479}
std::vector< Eigen::Index > activeMixtureNodes(const MaternMixture &rule)
void requireProductMixtureBudget(const MaternMixture &rule, Eigen::Index dimension)
double squaredExponentialGaussianDouble(const Eigen::MatrixXd &covariance, const Eigen::VectorXd &lengthscales)
void forEachProductMixtureNode(const MaternMixture &rule, const std::vector< Eigen::Index > &active, Eigen::Index dimension, Visitor &&visit)

◆ maternProductGaussianMeans()

Eigen::VectorXd gpr::bo::maternProductGaussianMeans ( const MaternMixture & rule,
const Eigen::MatrixXd & points,
const Eigen::VectorXd & mean,
const Eigen::MatrixXd & covariance,
const Eigen::VectorXd & lengthscales )
inline

Product Matérn kernel mean under a Gaussian with any covariance. Each axis is a gamma scale mixture of squared exponentials, so the product is a joint mixture of squared exponentials with diagonal scales, and each term has the closed full-covariance Gaussian moment.

Definition at line 435 of file BayesianQuadratureMoments.h.

439{
440 const Eigen::Index dimension = lengthscales.size();
441 requireProductMixtureBudget(rule, dimension);
442 const std::vector<Eigen::Index> active = activeMixtureNodes(rule);
443 std::vector<long double> sums(static_cast<std::size_t>(points.rows()),
444 0.0L);
446 rule, active, dimension,
447 [&](double weight, const Eigen::VectorXd& scales) {
448 const Eigen::VectorXd scaled = lengthscales.cwiseProduct(scales);
449 for (Eigen::Index row = 0; row < points.rows(); ++row) {
450 sums[static_cast<std::size_t>(row)] +=
451 static_cast<long double>(weight) *
452 squaredExponentialGaussianMean(points.row(row).transpose(),
453 mean, covariance, scaled);
454 }
455 });
456 Eigen::VectorXd result(points.rows());
457 for (Eigen::Index row = 0; row < points.rows(); ++row) {
458 result[row] = static_cast<double>(sums[static_cast<std::size_t>(row)]);
459 }
460 return result;
461}
double squaredExponentialGaussianMean(const Eigen::VectorXd &point, const Eigen::VectorXd &mean, const Eigen::MatrixXd &covariance, const Eigen::VectorXd &lengthscales)

◆ minimize() [1/2]

template<typename Objective>
ParameterSearchResult gpr::bo::minimize ( Objective && objective,
const std::vector< ParameterBound > & bounds,
const ParameterSearchConfig & config )

Default kernel: one length scale on every unit-cube axis, squared exponential. A categorical axis is compared for equality.

Definition at line 711 of file ParameterSearch.h.

714{
715 if (bounds.empty()) {
716 throw std::invalid_argument("parameter search needs a bound");
717 }
718 if (!(config.length_scale > 0.0) || !std::isfinite(config.length_scale)) {
719 throw std::invalid_argument("parameter search config is invalid");
720 }
721 std::vector<bool> categorical;
722 for (const ParameterBound& bound: bounds) {
723 categorical.push_back(bound.categorical);
724 }
725 const auto kernel = stationaryKernel(
727 Eigen::VectorXd::Constant(static_cast<Eigen::Index>(bounds.size()),
728 config.length_scale),
729 categorical),
730 SquaredExponential(1.0));
731 return minimize(std::forward<Objective>(objective), bounds, config, kernel);
732}
Squared Euclidean distance with one length scale, or one per coordinate.
k(r^2) = variance * exp(-r^2 / 2). The value at zero is the variance.
ParameterSearchResult minimize(Objective &&objective, const std::vector< ParameterBound > &bounds, const ParameterSearchConfig &config, const Kernel &kernel)
StationaryKernel< Distance, Radial > stationaryKernel(Distance distance, Radial radial)

◆ minimize() [2/2]

template<typename Objective, typename Kernel>
ParameterSearchResult gpr::bo::minimize ( Objective && objective,
const std::vector< ParameterBound > & bounds,
const ParameterSearchConfig & config,
const Kernel & kernel )

Definition at line 514 of file ParameterSearch.h.

518{
519 const int dimension = static_cast<int>(bounds.size());
520 if (dimension <= 0) {
521 throw std::invalid_argument("parameter search needs a bound");
522 }
523 if (config.candidate_count <= 0 || config.acquisition_evaluations < 0) {
524 throw std::invalid_argument("parameter search config is invalid");
525 }
526 bool discrete = false;
527 for (const ParameterBound& bound: bounds) {
528 validateBound(bound);
529 discrete = discrete || isDiscrete(bound);
530 }
531
532 const std::vector<int> primes = detail::firstPrimes(dimension);
533 int initial = config.initial_evaluations;
534 if (initial <= 0) initial = 4 * dimension;
535 if (initial < dimension + 1) initial = dimension + 1;
536
537 std::vector<Eigen::VectorXd> units;
538 std::vector<double> losses;
539 units.reserve(
540 static_cast<std::size_t>(initial + config.acquisition_evaluations));
541 losses.reserve(units.capacity());
542
543 // The stored coordinate is the lattice point the loss was called at,
544 // so the surrogate and the duplicate test see what was evaluated.
545 auto evaluate = [&](const Eigen::VectorXd& requested) {
546 const Eigen::VectorXd unit = detail::snapToLattice(requested, bounds);
547 Eigen::VectorXd theta(dimension);
548 for (int dim = 0; dim < dimension; ++dim) {
549 theta[dim] = unitToParameter(unit[dim], bounds[dim]);
550 }
551 const double loss = objective(theta);
552 if (!std::isfinite(loss)) {
553 throw std::runtime_error("parameter loss is not finite");
554 }
555 units.push_back(unit);
556 losses.push_back(loss);
557 return loss;
558 };
559
560 // A discrete box can hold fewer points than the initial design asks
561 // for: Halton points that round to a visited lattice point are skipped
562 // and the scan gives up after 64 points per requested evaluation.
563 int halton_used = 0;
564 for (int index = 1;
565 static_cast<int>(losses.size()) < initial && index <= 64 * initial;
566 ++index) {
567 halton_used = index;
568 const Eigen::VectorXd point = detail::snapToLattice(
569 detail::haltonPoint(index, dimension, primes), bounds);
570 if (discrete && detail::nearObserved(point, units, 1e-6)) continue;
571 evaluate(point);
572 }
573 int best = detail::bestLossIndex(losses);
574 double initial_lo = losses.front();
575 double initial_hi = losses.front();
576 for (double loss: losses) {
577 initial_lo = std::min(initial_lo, loss);
578 initial_hi = std::max(initial_hi, loss);
579 }
580 // 10^2.5 separates an exponential pair residual from a unit-square bowl.
581 // The simplex moves by fractions of an axis, which a lattice rounds
582 // away, so a box with a discrete axis is not polished.
583 const bool polish_valley =
584 !discrete && initial_lo >= 0.0 &&
585 initial_hi > std::pow(10.0, 2.5) * std::max(initial_lo, 1e-12);
586
588 gp.setNoiseVariance(config.noise_variance);
589
590 for (int step = 0; step < config.acquisition_evaluations; ++step) {
591 if (config.stop_loss >= 0.0 &&
592 losses[static_cast<std::size_t>(best)] <= config.stop_loss) {
593 break;
594 }
595 const int n = static_cast<int>(losses.size());
596 Eigen::MatrixXd inputs(n, dimension);
597 Eigen::VectorXd outputs(n);
598 double mean = 0.0;
599 for (int i = 0; i < n; ++i) {
600 inputs.row(i) = units[static_cast<std::size_t>(i)].transpose();
601 outputs[i] = losses[static_cast<std::size_t>(i)];
602 mean += outputs[i];
603 }
604 mean /= static_cast<double>(n);
605 double variance = 0.0;
606 for (int i = 0; i < n; ++i) {
607 const double delta = outputs[i] - mean;
608 variance += delta * delta;
609 }
610 variance /= static_cast<double>(std::max(n - 1, 1));
611 const double scale = std::sqrt(variance);
612 if (!(scale > 1e-14)) break;
613 outputs = (outputs.array() - mean) / scale;
614 const double best_standardized =
615 (losses[static_cast<std::size_t>(best)] - mean) / scale;
616
617 gp.setObservations(inputs, outputs);
618 if (!gp.fit()) {
619 throw std::runtime_error("scalar GP covariance is not definite");
620 }
621
622 std::vector<Eigen::VectorXd> candidates;
623 candidates.reserve(static_cast<std::size_t>(config.candidate_count) +
624 16);
625 const int halton_start =
626 halton_used + 1 + step * config.candidate_count;
627 for (int k = 0; k < config.candidate_count; ++k) {
628 candidates.push_back(
629 detail::haltonPoint(halton_start + k, dimension, primes));
630 }
631 detail::appendLocalCandidates(units[static_cast<std::size_t>(best)],
632 bounds, &candidates);
633 // Rounding happens here, inside the acquisition: the surrogate
634 // scores the lattice point that would be evaluated, and the
635 // observed-point test below drops one that already was.
636 for (Eigen::VectorXd& candidate: candidates) {
637 candidate = detail::snapToLattice(candidate, bounds);
638 }
639
640 double best_score = -std::numeric_limits<double>::infinity();
641 int chosen = -1;
642 constexpr int batch = 64;
643 for (int offset = 0; offset < static_cast<int>(candidates.size());
644 offset += batch) {
645 const int count =
646 std::min(batch, static_cast<int>(candidates.size()) - offset);
647 Eigen::MatrixXd queries(count, dimension);
648 std::vector<int> kept;
649 kept.reserve(static_cast<std::size_t>(count));
650 int row = 0;
651 for (int local = 0; local < count; ++local) {
652 const Eigen::VectorXd& point =
653 candidates[static_cast<std::size_t>(offset + local)];
654 if (detail::nearObserved(point, units, 1e-6)) continue;
655 queries.row(row) = point.transpose();
656 kept.push_back(offset + local);
657 ++row;
658 }
659 if (row == 0) continue;
660 Eigen::VectorXd predicted;
661 Eigen::VectorXd deviation;
662 gp.predict(queries.topRows(row), predicted, deviation);
663 for (int local = 0; local < row; ++local) {
664 const double mu = predicted[local];
665 const double sigma = deviation[local];
666 double score = 0.0;
667 if (config.acquisition ==
669 score = -lowerConfidenceBound(mu, sigma, config.ucb_kappa);
670 } else {
671 score = expectedImprovementForMinimum(mu, best_standardized,
672 sigma);
673 }
674 if (score > best_score) {
675 best_score = score;
676 chosen = kept[static_cast<std::size_t>(local)];
677 }
678 }
679 }
680 const bool improvement =
682 best_score > 0.0;
683 if (chosen < 0 || !improvement) break;
684 evaluate(candidates[static_cast<std::size_t>(chosen)]);
685 best = detail::bestLossIndex(losses);
686 }
687
688 if (polish_valley &&
689 !(config.stop_loss >= 0.0 &&
690 losses[static_cast<std::size_t>(best)] <= config.stop_loss)) {
691 detail::nelderMead(evaluate, units[static_cast<std::size_t>(best)],
692 losses[static_cast<std::size_t>(best)],
693 std::max(160, 40 * dimension), config.stop_loss);
694 best = detail::bestLossIndex(losses);
695 }
696
698 result.parameters.resize(dimension);
699 const Eigen::VectorXd& unit = units[static_cast<std::size_t>(best)];
700 for (int dim = 0; dim < dimension; ++dim) {
701 result.parameters[dim] = unitToParameter(unit[dim], bounds[dim]);
702 }
703 result.loss = losses[static_cast<std::size_t>(best)];
704 result.evaluations = static_cast<int>(losses.size());
705 return result;
706}
Kernel::covariance(left, right) is the prior covariance of two rows.
double unitToParameter(double unit, const ParameterBound &bound)
Map a unit-cube coordinate to the parameter of its axis.
void validateBound(const ParameterBound &bound)
Throw std::invalid_argument unless the axis is well formed.
bool isDiscrete(const ParameterBound &bound)
True for an integer axis or an axis with allowed values.
double lowerConfidenceBound(double mu, double sigma, double kappa)
Lower confidence bound for a minimizer, mu - kappa * sigma.
double variance(const Weights &w, const Matrix &covariance)
VecchiaResult evaluate(const Eigen::MatrixXd &points, const Eigen::VectorXd &y, double lengthscale, double noise, int max_neighbours)
int initial_evaluations
Zero selects 4 * dimension, and at least dimension + 1.
ParameterAcquisition acquisition
double stop_loss
Stop once the best loss is at or below this value. Negative disables.

◆ mixtureScale()

double gpr::bo::mixtureScale ( double node,
double nu )
inline

Definition at line 233 of file BayesianQuadratureMoments.h.

234{
235 return std::sqrt(node / nu);
236}

◆ parameterToUnit()

double gpr::bo::parameterToUnit ( double parameter,
const ParameterBound & bound )
inline

Unit-cube coordinate of a parameter, the inverse of unitToParameter().

Allowed value i of k sits at i / (k - 1), and at 0.5 when k is one. A parameter that is not an allowed value takes the coordinate of the nearest one. Other axes are clamped to [0, 1].

Definition at line 203 of file ParameterSearch.h.

204{
205 if (!bound.allowed_values.empty()) {
206 const std::size_t count = bound.allowed_values.size();
207 std::size_t nearest = 0;
208 for (std::size_t i = 1; i < count; ++i) {
209 if (std::abs(bound.allowed_values[i] - parameter) <
210 std::abs(bound.allowed_values[nearest] - parameter)) {
211 nearest = i;
212 }
213 }
214 return count == 1 ? 0.5
215 : static_cast<double>(nearest) /
216 static_cast<double>(count - 1);
217 }
218 double unit = 0.0;
219 if (bound.logarithmic) {
220 unit = (std::log(parameter) - std::log(bound.lower)) /
221 (std::log(bound.upper) - std::log(bound.lower));
222 } else {
223 unit = (parameter - bound.lower) / (bound.upper - bound.lower);
224 }
225 if (!(unit >= 0.0)) return 0.0;
226 return std::min(1.0, unit);
227}

◆ probabilityOfFeasibility()

double gpr::bo::probabilityOfFeasibility ( double mu,
double sigma,
double threshold = 0.0 )
inline

Probability that a normal constraint value is feasible.

P(c <= threshold) for c normal with mean mu and standard deviation sigma, which is Phi((threshold - mu) / sigma). A zero sigma gives one when mu is at most the threshold and zero otherwise. A non-finite input or a negative sigma gives zero.

Definition at line 60 of file ExpectedImprovement.h.

62{
63 if (!(sigma >= 0.0) || !std::isfinite(sigma) || !std::isfinite(mu) ||
64 !std::isfinite(threshold)) {
65 return 0.0;
66 }
67 if (sigma == 0.0) return mu <= threshold ? 1.0 : 0.0;
68 return 0.5 * std::erfc(-(threshold - mu) / (sigma * std::sqrt(2.0)));
69}

◆ productRadial()

template<typename Left, typename Right>
ProductRadial< Left, Right > gpr::bo::productRadial ( Left left,
Right right )

Definition at line 700 of file StationaryKernel.h.

701{
702 return ProductRadial<Left, Right>(std::move(left), std::move(right));
703}
f * g on one squared distance.

◆ requireProductMixtureBudget()

void gpr::bo::requireProductMixtureBudget ( const MaternMixture & rule,
Eigen::Index dimension )
inline

Definition at line 384 of file BayesianQuadratureMoments.h.

386{
387 const double per_axis =
388 static_cast<double>(activeMixtureNodes(rule).size());
389 const double joint = std::pow(per_axis, static_cast<double>(dimension));
390 if (joint > kMaxProductMixtureNodes) {
391 throw std::domain_error(
392 "product Matern under a non-diagonal Gaussian needs " +
393 std::to_string(static_cast<long long>(per_axis)) + "^" +
394 std::to_string(static_cast<long long>(dimension)) +
395 " joint mixture nodes, above the limit of " +
396 std::to_string(static_cast<long long>(kMaxProductMixtureNodes)) +
397 "; use a diagonal covariance, an isotropic Matern kernel, or a "
398 "squared-exponential kernel");
399 }
400}
constexpr double kMaxProductMixtureNodes

◆ requireSymmetricCovariance()

void gpr::bo::requireSymmetricCovariance ( const Eigen::MatrixXd & covariance)
inline

A covariance is read through its lower triangle by the Cholesky factor, so an asymmetric matrix would be integrated as a different, symmetric one. Reject it instead. The tolerance is roundoff of the matrix's own scale.

Definition at line 292 of file BayesianQuadratureMoments.h.

293{
294 if (covariance.rows() != covariance.cols()) {
295 throw std::invalid_argument(
296 "Gaussian measure covariance is not square");
297 }
298 const double scale = covariance.cwiseAbs().maxCoeff();
299 const double asymmetry =
300 (covariance - covariance.transpose()).cwiseAbs().maxCoeff();
301 if (!(asymmetry <= 1e-12 * scale)) {
302 throw std::invalid_argument(
303 "Gaussian measure covariance is not symmetric");
304 }
305}

◆ scalarLogMarginalLikelihood()

double gpr::bo::scalarLogMarginalLikelihood ( const ScalarLikelihoodData & data,
const ScalarHyperparameters & hyper,
Eigen::VectorXd * gradient = nullptr )
inline

Log marginal likelihood log p(y | X, theta) and its gradient.

With K = k(X, X) + diag(noise), the value is -1/2 y^T K^-1 y - 1/2 log|K| - n/2 log(2 pi). With a basis H of p columns it is -1/2 y^T P y - 1/2 log|K| - 1/2 log|H^T K^-1 H|

  • (n - p)/2 log(2 pi), P = K^-1 - K^-1 H (H^T K^-1 H)^-1 H^T K^-1.
Parameters
gradientOptional. Receives scalarParameterCount() derivatives with respect to the logarithms of the length scales, of the signal variance and, without per-row variances, of the noise variance, in that order: 1/2 tr((a a^T - P) dK/dtheta), a = P y.
Returns
The value, or minus infinity when K or H^T K^-1 H is not positive definite. The gradient is then not written.

Definition at line 124 of file ScalarHyperparameterFit.h.

127{
128 detail::requireLikelihoodInputs(data, hyper);
129 const Eigen::Index n = data.x.rows();
130 const Eigen::Index dimension = data.x.cols();
131 const Eigen::Index basis_count = data.basis.cols();
132 const bool shared_noise = data.noise_variances.size() == 0;
133 const double failed = -std::numeric_limits<double>::infinity();
134 const RadialShape radial(data.radial, hyper.signal_variance);
135
136 // Separation of rows i and j on one axis, in length-scale units.
137 auto scaledDelta = [&](Eigen::Index i, Eigen::Index j, Eigen::Index dim) {
138 const double delta =
139 !data.categorical.empty() &&
140 data.categorical[static_cast<std::size_t>(dim)]
141 ? (data.x(i, dim) != data.x(j, dim) ? 1.0 : 0.0)
142 : data.x(i, dim) - data.x(j, dim);
143 return delta / hyper.length_scales[dim];
144 };
145 auto squaredDistance = [&](Eigen::Index i, Eigen::Index j) {
146 double squared = 0.0;
147 for (Eigen::Index dim = 0; dim < dimension; ++dim) {
148 const double scaled = scaledDelta(i, j, dim);
149 squared += scaled * scaled;
150 }
151 return squared;
152 };
153
154 EigenMatrix signal(n, n);
155 for (Eigen::Index j = 0; j < n; ++j) {
156 for (Eigen::Index i = j; i < n; ++i) {
157 const double value = radial(squaredDistance(i, j));
158 signal(i, j) = value;
159 signal(j, i) = value;
160 }
161 }
162 EigenMatrix covariance = signal;
163 for (Eigen::Index i = 0; i < n; ++i) {
164 covariance(i, i) +=
165 shared_noise ? hyper.noise_variance : data.noise_variances[i];
166 }
167 EigenMatrix factor;
168 if (!covariance.allFinite() || !gpr::linalg::cholesky(covariance, factor)) {
169 return failed;
170 }
171 const EigenMatrix identity = EigenMatrix::Identity(n, n);
172 // P starts as K^-1 and loses the span of the basis below.
174 factor, gpr::linalg::forward_solve_mat(factor, identity));
175 projector = 0.5 * (projector + projector.transpose()).eval();
176 double basis_log_determinant = 0.0;
177 if (basis_count > 0) {
178 const Eigen::MatrixXd precision_basis = projector * data.basis;
179 Eigen::MatrixXd information = data.basis.transpose() * precision_basis;
180 information = 0.5 * (information + information.transpose()).eval();
181 const Eigen::LLT<Eigen::MatrixXd> information_factor(information);
182 if (information_factor.info() != Eigen::Success) return failed;
183 const Eigen::MatrixXd lower = information_factor.matrixL();
184 basis_log_determinant = 2.0 * lower.diagonal().array().log().sum();
185 projector -= precision_basis *
186 information_factor.solve(precision_basis.transpose());
187 }
188 const Eigen::VectorXd alpha = projector * data.y;
189 const double two_pi = 2.0 * std::acos(-1.0);
190 const double value =
191 -0.5 * data.y.dot(alpha) - gpr::linalg::log_det_cholesky(factor) -
192 0.5 * basis_log_determinant -
193 0.5 * static_cast<double>(n - basis_count) * std::log(two_pi);
194 if (!std::isfinite(value)) return failed;
195 if (gradient == nullptr) return value;
196
197 // weight = a a^T - P, so each derivative is 1/2 sum_ij weight_ij dK_ij.
198 const EigenMatrix weight = alpha * alpha.transpose() - projector;
199 gradient->setZero(scalarParameterCount(data));
200 for (Eigen::Index j = 0; j < n; ++j) {
201 for (Eigen::Index i = j + 1; i < n; ++i) {
202 const double slope = radial.derivative(squaredDistance(i, j));
203 for (Eigen::Index dim = 0; dim < dimension; ++dim) {
204 const double scaled = scaledDelta(i, j, dim);
205 // d r^2 / d log(l_dim) = -2 (delta_dim / l_dim)^2, and the
206 // pair (i, j) appears twice in the symmetric sum.
207 (*gradient)[dim] +=
208 weight(i, j) * slope * (-2.0 * scaled * scaled);
209 }
210 }
211 }
212 (*gradient)[dimension] = 0.5 * weight.cwiseProduct(signal).sum();
213 if (shared_noise) {
214 (*gradient)[dimension + 1] =
215 0.5 * hyper.noise_variance * weight.diagonal().sum();
216 }
217 return value;
218}
One of SquaredExponential, Matern32 and Matern52 behind a tag.
EigenMatrix back_solve_mat(const EigenMatrix &L, const EigenMatrix &B)
Back triangular solve with matrix RHS (BLAS equivalent: dtrsm with side=L, uplo=L,...
EigenMatrix forward_solve_mat(const EigenMatrix &L, const EigenMatrix &B)
Forward triangular solve with matrix RHS (BLAS equivalent: dtrsm).
double log_det_cholesky(const EigenMatrix &L)
Half log-determinant from Cholesky factor.
bool cholesky(const EigenMatrix &C, EigenMatrix &L)
Cholesky decomposition (LAPACK equivalent: dpotrf).
double squaredDistance(const Eigen::VectorXd &a, const Eigen::VectorXd &b)
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
Eigen::MatrixXd basis
Row i is phi(x_i)^T of the mean basis. Zero columns: zero mean.

◆ scalarParameterCount()

Eigen::Index gpr::bo::scalarParameterCount ( const ScalarLikelihoodData & data)
inline

Number of fitted parameters: the length scales, the signal variance and, without per-row variances, the noise variance.

Definition at line 61 of file ScalarHyperparameterFit.h.

62{
63 return data.x.cols() + 1 + (data.noise_variances.size() == 0 ? 1 : 0);
64}

◆ scaledRadial()

template<typename Radial>
ScaledRadial< Radial > gpr::bo::scaledRadial ( double scale,
Radial radial )

Definition at line 688 of file StationaryKernel.h.

689{
690 return ScaledRadial<Radial>(scale, std::move(radial));
691}
c * f. The scale is finite and may be negative. The leaf keeps its variance.

◆ snapUnit()

double gpr::bo::snapUnit ( double unit,
const ParameterBound & bound )
inline

The unit-cube coordinate of the lattice point a coordinate rounds to. A continuous axis returns the clamped coordinate.

Definition at line 231 of file ParameterSearch.h.

232{
233 if (!isDiscrete(bound)) return std::min(1.0, std::max(0.0, unit));
234 return parameterToUnit(unitToParameter(unit, bound), bound);
235}
double parameterToUnit(double parameter, const ParameterBound &bound)
Unit-cube coordinate of a parameter, the inverse of unitToParameter().

◆ squaredExponentialBoxCross()

double gpr::bo::squaredExponentialBoxCross ( const Eigen::VectorXd & lower,
const Eigen::VectorXd & first_upper,
const Eigen::VectorXd & second_upper,
const Eigen::VectorXd & lengthscales )
inline

Definition at line 59 of file BayesianQuadratureMoments.h.

63{
64 long double value = 1.0L;
65 const SquaredExponential radial(1.0);
66 for (Eigen::Index dim = 0; dim < lower.size(); ++dim) {
67 const auto primitive = [&](double distance) {
68 return 0.5 * kernelDoubleIntegral1D(radial, 0.0, std::abs(distance),
69 lengthscales[dim]);
70 };
71 const double a = lower[dim];
72 const double b = first_upper[dim];
73 const double c = lower[dim];
74 const double d = second_upper[dim];
75 value *= primitive(d - a) - primitive(c - a) - primitive(d - b) +
76 primitive(c - b);
77 }
78 return static_cast<double>(value);
79}

◆ squaredExponentialBoxDouble()

double gpr::bo::squaredExponentialBoxDouble ( const Eigen::VectorXd & lower,
const Eigen::VectorXd & upper,
const Eigen::VectorXd & lengthscales )
inline

Definition at line 46 of file BayesianQuadratureMoments.h.

49{
50 long double value = 1.0L;
51 const SquaredExponential radial(1.0);
52 for (Eigen::Index dim = 0; dim < lower.size(); ++dim) {
53 value *= kernelDoubleIntegral1D(radial, lower[dim], upper[dim],
54 lengthscales[dim]);
55 }
56 return static_cast<double>(value);
57}

◆ squaredExponentialBoxMean()

double gpr::bo::squaredExponentialBoxMean ( const Eigen::VectorXd & point,
const Eigen::VectorXd & lower,
const Eigen::VectorXd & upper,
const Eigen::VectorXd & lengthscales )
inline

Definition at line 32 of file BayesianQuadratureMoments.h.

36{
37 long double value = 1.0L;
38 const SquaredExponential radial(1.0);
39 for (Eigen::Index dim = 0; dim < point.size(); ++dim) {
40 value *= kernelMean1D(radial, point[dim], lower[dim], upper[dim],
41 lengthscales[dim]);
42 }
43 return static_cast<double>(value);
44}

◆ squaredExponentialGaussian1D()

double gpr::bo::squaredExponentialGaussian1D ( double point,
double mean,
double variance,
double lengthscale )
inline

Definition at line 352 of file BayesianQuadratureMoments.h.

354{
355 const double length_squared = lengthscale * lengthscale;
356 const double delta = point - mean;
357 return lengthscale / std::sqrt(length_squared + variance) *
358 std::exp(-0.5 * delta * delta / (length_squared + variance));
359}

◆ squaredExponentialGaussianDouble()

double gpr::bo::squaredExponentialGaussianDouble ( const Eigen::MatrixXd & covariance,
const Eigen::VectorXd & lengthscales )
inline

Definition at line 331 of file BayesianQuadratureMoments.h.

333{
334 requireSymmetricCovariance(covariance);
335 const Eigen::Index dimension = lengthscales.size();
336 Eigen::MatrixXd shifted = 2.0 * covariance;
337 double log_det_length = 0.0;
338 for (Eigen::Index dim = 0; dim < dimension; ++dim) {
339 const double length_squared = lengthscales[dim] * lengthscales[dim];
340 shifted(dim, dim) += length_squared;
341 log_det_length += std::log(length_squared);
342 }
343 Eigen::LLT<Eigen::MatrixXd> factor(shifted);
344 if (factor.info() != Eigen::Success) {
345 throw std::invalid_argument("Gaussian measure covariance is not SPD");
346 }
347 const double log_det_shifted =
348 2.0 * factor.matrixL().toDenseMatrix().diagonal().array().log().sum();
349 return std::exp(0.5 * (log_det_length - log_det_shifted));
350}
void requireSymmetricCovariance(const Eigen::MatrixXd &covariance)

◆ squaredExponentialGaussianDouble1D()

double gpr::bo::squaredExponentialGaussianDouble1D ( double variance,
double lengthscale )
inline

Definition at line 361 of file BayesianQuadratureMoments.h.

363{
364 const double length_squared = lengthscale * lengthscale;
365 return lengthscale / std::sqrt(length_squared + 2.0 * variance);
366}

◆ squaredExponentialGaussianMean()

double gpr::bo::squaredExponentialGaussianMean ( const Eigen::VectorXd & point,
const Eigen::VectorXd & mean,
const Eigen::MatrixXd & covariance,
const Eigen::VectorXd & lengthscales )
inline

Definition at line 307 of file BayesianQuadratureMoments.h.

310{
311 requireSymmetricCovariance(covariance);
312 const Eigen::Index dimension = lengthscales.size();
313 Eigen::MatrixXd shifted = covariance;
314 double log_det_length = 0.0;
315 for (Eigen::Index dim = 0; dim < dimension; ++dim) {
316 const double length_squared = lengthscales[dim] * lengthscales[dim];
317 shifted(dim, dim) += length_squared;
318 log_det_length += std::log(length_squared);
319 }
320 Eigen::LLT<Eigen::MatrixXd> factor(shifted);
321 if (factor.info() != Eigen::Success) {
322 throw std::invalid_argument("Gaussian measure covariance is not SPD");
323 }
324 const double log_det_shifted =
325 2.0 * factor.matrixL().toDenseMatrix().diagonal().array().log().sum();
326 const Eigen::VectorXd delta = point - mean;
327 const double quadratic = delta.dot(factor.solve(delta));
328 return std::exp(0.5 * (log_det_length - log_det_shifted) - 0.5 * quadratic);
329}

◆ stationaryKernel()

template<typename Distance, typename Radial>
requires SquaredDistance<Distance> && RadialFunction<Radial>
StationaryKernel< Distance, Radial > gpr::bo::stationaryKernel ( Distance distance,
Radial radial )

Definition at line 746 of file StationaryKernel.h.

748{
749 return StationaryKernel<Distance, Radial>(std::move(distance),
750 std::move(radial));
751}
Covariance k(d(x, x')). Distance::squared and Radial::operator()(double).

◆ sumRadial()

template<typename Left, typename Right>
SumRadial< Left, Right > gpr::bo::sumRadial ( Left left,
Right right )

Definition at line 694 of file StationaryKernel.h.

695{
696 return SumRadial<Left, Right>(std::move(left), std::move(right));
697}
f + g on one squared distance.

◆ unitToParameter()

double gpr::bo::unitToParameter ( double unit,
const ParameterBound & bound )
inline

Map a unit-cube coordinate to the parameter of its axis.

An axis with k allowed values splits [0, 1] into k equal cells. An integer axis maps as the continuous one does and rounds to the nearest whole number in the interval.

Definition at line 170 of file ParameterSearch.h.

171{
172 const double clamped = std::min(1.0, std::max(0.0, unit));
173 if (!bound.allowed_values.empty()) {
174 const std::size_t count = bound.allowed_values.size();
175 const std::size_t index = std::min(
176 count - 1, static_cast<std::size_t>(
177 std::floor(clamped * static_cast<double>(count))));
178 return bound.allowed_values[index];
179 }
180 double value = 0.0;
181 if (bound.logarithmic) {
182 value =
183 std::exp(std::log(bound.lower) +
184 clamped * (std::log(bound.upper) - std::log(bound.lower)));
185 } else {
186 value = bound.lower + clamped * (bound.upper - bound.lower);
187 }
188 if (bound.integer) {
189 value = std::min(std::floor(bound.upper),
190 std::max(std::ceil(bound.lower), std::round(value)));
191 }
192 return value;
193}

◆ validateBound()

void gpr::bo::validateBound ( const ParameterBound & bound)
inline

Throw std::invalid_argument unless the axis is well formed.

Definition at line 133 of file ParameterSearch.h.

134{
135 if (!bound.allowed_values.empty()) {
136 for (std::size_t i = 0; i < bound.allowed_values.size(); ++i) {
137 if (!std::isfinite(bound.allowed_values[i])) {
138 throw std::invalid_argument("allowed value is not finite");
139 }
140 for (std::size_t j = 0; j < i; ++j) {
141 if (bound.allowed_values[i] == bound.allowed_values[j]) {
142 throw std::invalid_argument("allowed value is repeated");
143 }
144 }
145 }
146 return;
147 }
148 if (bound.categorical) {
149 throw std::invalid_argument("categorical axis needs allowed values");
150 }
151 if (!(bound.upper > bound.lower) || !std::isfinite(bound.lower) ||
152 !std::isfinite(bound.upper)) {
153 throw std::invalid_argument("parameter bound is empty");
154 }
155 if (bound.logarithmic && !(bound.lower > 0.0)) {
156 throw std::invalid_argument("logarithmic bound must be positive");
157 }
158 if (bound.integer && !(std::floor(bound.upper) >= std::ceil(bound.lower))) {
159 throw std::invalid_argument("integer bound holds no whole number");
160 }
161}

Variable Documentation

◆ kMaxProductMixtureNodes

double gpr::bo::kMaxProductMixtureNodes = 2.0e5
inlineconstexpr

Largest number of joint mixture nodes the product-Matérn moments under a non-diagonal Gaussian will evaluate. With the nodes of the accurate one-dimensional rule this admits two dimensions and no more.

Definition at line 371 of file BayesianQuadratureMoments.h.