Loading...
Searching...
No Matches
Ceres.inl
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
5#include <ceres/ceres.h>
6
7#include <cfloat>
8#include <vector>
9
10namespace funcmin {
11
12template <typename ClassName, typename FuncName>
13class GprCostFunction : public ceres::CostFunction {
14public:
16 const Eigen::VectorXd& x_ind_data,
17 const Eigen::VectorXd& y_data, FuncName func,
18 ClassName& gpr_instance)
19 : x_(x_data),
20 x_ind_(x_ind_data),
21 y_(y_data),
22 func_to_min_(func),
23 holder_(gpr_instance),
24 normalization_factor_(-1.0)
25 {
26 const int n_vars = holder_.sexpat_cov_func->combineParameters().size();
27 mutable_parameter_block_sizes()->push_back(n_vars);
28 set_num_residuals(1);
29 }
30
31 virtual ~GprCostFunction() { }
32
33 virtual bool Evaluate(double const* const* parameters, double* residuals,
34 double** jacobians) const override
35 {
36 const int n_vars = parameter_block_sizes()[0];
37 Eigen::Map<const Eigen::VectorXd> w_current(parameters[0], n_vars);
38
39 double raw_energy;
40
41 if (jacobians != nullptr && jacobians[0] != nullptr) {
42 Eigen::VectorXd raw_gradient(n_vars);
43 gpr::EnergyAndGradient eg(raw_energy, raw_gradient);
44
45 // 1. Call your function to get the raw, unscaled energy and
46 // gradient.
47 (holder_.*func_to_min_)(w_current, x_, x_ind_, y_, eg);
48
49 // 2. On the first evaluation, compute the normalization factor.
50 if (normalization_factor_ < 0.0) {
51 normalization_factor_ = raw_gradient.norm();
52 if (normalization_factor_ < DBL_EPSILON) {
53 normalization_factor_ = 1.0;
54 }
55 }
56
57 // 3. Scale BOTH the energy (residual) and the gradient (Jacobian).
58 residuals[0] = raw_energy / normalization_factor_;
59 Eigen::Map<Eigen::VectorXd> jacobian_map(jacobians[0], n_vars);
60 jacobian_map = raw_gradient / normalization_factor_;
61
62 // --- THE HACK HAS BEEN REMOVED ---
63 // const double sign_correction = (residuals[0] < 0.0) ? -1.0 : 1.0;
64 // jacobian_map *= sign_correction;
65
66 } else {
67 // Gradient is not requested.
68 Eigen::VectorXd grad_dummy;
69 gpr::EnergyAndGradient eg(raw_energy, grad_dummy);
70 (holder_.*func_to_min_)(w_current, x_, x_ind_, y_, eg);
71
72 // Still scale the residual even if jacobian is not requested.
73 if (normalization_factor_ > 0.0) {
74 residuals[0] = raw_energy / normalization_factor_;
75 } else {
76 residuals[0] = raw_energy; // Not initialized yet
77 }
78 }
79
80 return std::isfinite(residuals[0]);
81 }
82
83private:
84 const gpr::EigenMatrix& x_;
85 const Eigen::VectorXd& x_ind_;
86 const Eigen::VectorXd& y_;
87 FuncName func_to_min_;
88 ClassName& holder_;
89 mutable double normalization_factor_;
90};
91
92template <typename ClassName, typename FuncName>
94 const Eigen::VectorXd& x_ind, const Eigen::VectorXd& y,
95 Eigen::VectorXd& w, FuncName func_to_min,
96 ClassName& holder, double)
97{
98 const int n_vars = w.size();
99 this->failedOptim = true;
100 if (n_vars == 0) {
101 this->failedOptim = false;
102 return;
103 }
104
105 Eigen::VectorXd lower_bounds(n_vars);
106 Eigen::VectorXd upper_bounds(n_vars);
107 for (int i = 0; i < n_vars; ++i) {
108 lower_bounds(i) = std::log(0.2);
109 upper_bounds(i) = std::log(3.0);
110 }
111 upper_bounds(0) = std::log(10);
112
113 ceres::Problem problem;
114 ceres::CostFunction* cost_function =
115 new GprCostFunction<ClassName, FuncName>(x_data, x_ind, y, func_to_min,
116 holder);
117 problem.AddResidualBlock(cost_function, new ceres::TrivialLoss(), w.data());
118
119 for (int i = 0; i < n_vars; ++i) {
120 problem.SetParameterLowerBound(w.data(), i, lower_bounds(i));
121 problem.SetParameterUpperBound(w.data(), i, upper_bounds(i));
122 }
123
124 ceres::Solver::Options options;
125 options.function_tolerance = settings.common.tolerance_func;
126 options.gradient_tolerance = settings.common.tolerance_sol;
127 options.linear_solver_type = ceres::DENSE_QR;
128 options.line_search_direction_type = ceres::LBFGS;
129 options.max_num_iterations = settings.common.max_iter;
130 options.minimizer_progress_to_stdout = (settings.common.report_level >= 2);
131
132 ceres::Solver::Summary summary;
133 ceres::Solve(options, &problem, &summary);
134
135 if (summary.IsSolutionUsable()) {
136 this->failedOptim = false;
137 }
138}
139
141 const gpr::CeresOptimizationSettings& _settings)
142{
143 settings = _settings;
144}
145
146} // namespace funcmin
@ y
Definition Enums.h:28
void optimize(const gpr::EigenMatrix &x_data, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, Eigen::VectorXd &w, FuncName func_to_min, ClassName &holder, double)
Definition Ceres.inl:93
void setAlgorithmSettings(const gpr::CeresOptimizationSettings &_settings)
Definition Ceres.inl:140
bool failedOptim
Definition Ceres.h:26
virtual bool Evaluate(double const *const *parameters, double *residuals, double **jacobians) const override
Definition Ceres.inl:33
virtual ~GprCostFunction()
Definition Ceres.inl:31
GprCostFunction(const gpr::EigenMatrix &x_data, const Eigen::VectorXd &x_ind_data, const Eigen::VectorXd &y_data, FuncName func, ClassName &gpr_instance)
Definition Ceres.inl:15
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
Ceres-specific settings (currently only the common fields).
Definition Structures.h:347
Structure of energy and gradient stored in Eigen-compatible form.
Definition Structures.h:359