Loading...
Searching...
No Matches
ScopedKernelState.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
5#ifndef GPR_ML_LAPLACE_SCOPED_KERNEL_STATE_H_
6#define GPR_ML_LAPLACE_SCOPED_KERNEL_STATE_H_
7
11
12namespace gpr {
13namespace laplace {
14
23public:
28 ScopedKernelState(SexpatCF& kernel, double& sigma2,
29 LikGaussian* likelihood = nullptr) noexcept
30 : kernel_(kernel),
31 sigma2_ref_(sigma2),
32 likelihood_(likelihood),
33 saved_magn_(kernel.getMagnSigma2()),
34 saved_ls_(kernel.getLengthScaleRef()),
35 saved_sigma2_(sigma2),
36 saved_likelihood_sigma2_(
37 likelihood != nullptr ? likelihood->getSigma2() : 0.0)
38 {
39 }
40
42 {
43 restore();
44 }
45
51 void restore() noexcept
52 {
53 kernel_.setMagnSigma2(saved_magn_);
54 kernel_.getLengthScaleRef() = saved_ls_;
55 sigma2_ref_ = saved_sigma2_;
56 if (likelihood_ != nullptr) {
57 likelihood_->setSigma2(saved_likelihood_sigma2_);
58 }
59 }
60
65
68 void applyTheta(const Eigen::VectorXd& theta)
69 {
70 if (theta.size() < 2) return;
71 kernel_.setMagnSigma2(std::exp(theta(0)));
72 auto& ls = kernel_.getLengthScaleRef();
73 const int n_ls = static_cast<int>(ls.size());
74 const int n_cov = 1 + n_ls;
75 for (int i = 0; i < n_ls && (1 + i) < theta.size(); ++i) {
76 ls(0, i) = std::exp(theta(1 + i));
77 }
78 if (theta.size() > n_cov) {
79 const double noise = std::exp(theta(theta.size() - 1));
80 sigma2_ref_ = noise;
81 if (likelihood_ != nullptr) {
82 likelihood_->setSigma2(noise);
83 }
84 }
85 }
86
87private:
88 SexpatCF& kernel_;
89 double& sigma2_ref_;
90 LikGaussian* const likelihood_;
91 const double saved_magn_;
92 const FieldMatrixd saved_ls_;
93 const double saved_sigma2_;
94 const double saved_likelihood_sigma2_;
95};
96
97} // namespace laplace
98} // namespace gpr
99
100#endif // GPR_ML_LAPLACE_SCOPED_KERNEL_STATE_H_
Gaussian noise with variance.
Definition LikGaussian.h:29
Pair-type inverse-distance squared-exponential primitive.
Definition SexpatCF.h:74
ScopedKernelState(ScopedKernelState &&)=delete
void applyTheta(const Eigen::VectorXd &theta)
ScopedKernelState & operator=(ScopedKernelState &&)=delete
ScopedKernelState(SexpatCF &kernel, double &sigma2, LikGaussian *likelihood=nullptr) noexcept
ScopedKernelState & operator=(const ScopedKernelState &)=delete
ScopedKernelState(const ScopedKernelState &)=delete
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Definition Macros.h:25