Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
solver.cpp
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
9
11#include "momentum/common/log.h"
14
15#include <gsl/narrow>
16
17namespace momentum {
18
19template <typename T>
21 : solverFunction_(solver) {
22 numParameters_ = solverFunction_->getNumParameters();
23 actualParameters_ = gsl::narrow<int>(numParameters_);
25 activeParameters_.flip();
26
28 setOptions(options);
29}
30
31template <typename T>
33 minIterations_ = options.minIterations;
34 maxIterations_ = options.maxIterations;
35 threshold_ = options.threshold;
36 verbose_ = options.verbose;
37}
38
39template <typename T>
41 activeParameters_ = parameterSet;
42
44
45 solverFunction_->setEnabledParameters(parameterSet);
46 actualParameters_ = gsl::narrow<int>(solverFunction_->getActualParameters());
47}
48
49template <typename T>
50double SolverT<T>::solve(Eigen::VectorX<T>& params) {
52
53 if (storeHistory) {
54 auto& parameterHistory = iterationHistory_["parameters"];
55 auto& errorHistory = iterationHistory_["error"];
56 auto& iterationCount = iterationHistory_["iterations"];
57 if (parameterHistory.rows() != gsl::narrow_cast<Eigen::Index>(numParameters_) ||
58 parameterHistory.cols() != gsl::narrow_cast<Eigen::Index>(maxIterations_)) {
59 parameterHistory.resize(numParameters_, maxIterations_);
60 }
61 if (errorHistory.rows() != gsl::narrow_cast<Eigen::Index>(maxIterations_) ||
62 errorHistory.cols() != 1) {
63 errorHistory.resize(maxIterations_, 1);
64 }
65 if (iterationCount.rows() != 1 || iterationCount.cols() != 1) {
66 iterationCount.resize(1, 1);
67 }
68
69 parameterHistory.setZero();
70 errorHistory.setZero();
71 iterationCount.setZero();
72 }
73
74 errorHistory_.clear();
75 errorHistory_.reserve(maxIterations_);
76
77 MT_CHECK(params.size() == gsl::narrow<Eigen::DenseIndex>(numParameters_));
78 parameters_ = params;
79
80 static_assert(
81 std::is_same<decltype(error_), decltype(lastError_)>::value,
82 "error and lastError_ should be of the same type");
83 error_ = std::numeric_limits<decltype(error_)>::max();
84 lastError_ = std::numeric_limits<decltype(lastError_)>::max();
85
87
88 iteration_ = 0;
89 for (; iteration_ < maxIterations_; iteration_++) {
90 // do actual iteration (iterations should update the error value)
92 errorHistory_.push_back(error_);
93
94 MT_LOGI_IF(this->verbose_, "Iteration: {}, error: {}", this->iteration_, error_);
95
96 // check for convergence
97 bool converged = false;
98 if (std::fabs(lastError_ - error_) / (std::fabs(error_) + std::numeric_limits<float>::min()) <=
99 threshold_ * std::numeric_limits<float>::epsilon()) {
100 converged = true;
101 }
102
103 // set history
104 if (storeHistory) {
105 auto& parameterHistory = iterationHistory_["parameters"];
106 auto& errorHistory = iterationHistory_["error"];
107 parameterHistory.col(iteration_) = parameters_;
108 errorHistory(iteration_, 0) = gsl::narrow_cast<float>(error_);
109
110 solverFunction_->storeHistory(iterationHistory_, iteration_, maxIterations_);
111 }
112
113 if (iteration_ >= minIterations_ && converged) {
114 break;
115 }
116
117 // update last error
119 }
120
121 if (storeHistory) {
122 auto& iterationCount = iterationHistory_["iterations"];
123 iterationCount(0, 0) = gsl::narrow_cast<float>(iteration_);
124 }
125
126 params = parameters_;
127 return error_;
128}
129
130template <typename T>
134
135template <typename T>
136void SolverT<T>::setParameters(const Eigen::VectorX<T>& params) {
137 parameters_ = params;
138}
139
140template <typename T>
141void SolverT<T>::setStoreHistory(const bool b) {
142 storeHistory = b;
143}
144
145template <typename T>
146const std::unordered_map<std::string, Eigen::MatrixX<T>>& SolverT<T>::getHistory() const {
147 return iterationHistory_;
148}
149
150template <typename T>
152 return minIterations_;
153}
154
155template <typename T>
157 return maxIterations_;
158}
159
160template class SolverT<float>;
161template class SolverT<double>;
162
163} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
Abstract base class for optimization objective functions.
Base class for numerical optimization solvers.
Definition solver.h:41
bool newParameterPattern_
Flag indicating parameter structure has changed.
Definition solver.h:120
virtual void setOptions(const SolverOptions &options)
Updates solver configuration with new options.
Definition solver.cpp:32
virtual void doIteration()=0
Performs a single iteration of the optimization algorithm.
void setParameters(const Eigen::VectorX< T > &params)
Sets the current parameter values without solving.
Definition solver.cpp:136
std::unordered_map< std::string, Eigen::MatrixX< T > > iterationHistory_
Recorded data from optimization process.
Definition solver.h:137
size_t getMaxIterations() const
Returns the maximum number of iterations before terminating.
Definition solver.cpp:156
const ParameterSet & getActiveParameters() const
Returns the current set of enabled parameters.
Definition solver.cpp:131
double lastError_
Previous iteration's objective function value.
Definition solver.h:129
ParameterSet activeParameters_
Bitset indicating which parameters are enabled for optimization.
Definition solver.h:112
size_t iteration_
Current iteration count.
Definition solver.h:123
Eigen::VectorX< T > parameters_
Current parameter values.
Definition solver.h:109
bool verbose_
Whether to output detailed progress information.
Definition solver.h:142
size_t getMinIterations() const
Returns the minimum number of iterations before checking convergence.
Definition solver.cpp:151
bool storeHistory
Whether to record optimization progress for analysis.
Definition solver.h:132
double error_
Current objective function value.
Definition solver.h:126
const std::unordered_map< std::string, Eigen::MatrixX< T > > & getHistory() const
Returns the history of the solver's iterations.
Definition solver.cpp:146
void setStoreHistory(bool b)
Controls whether to store iteration history for debugging and analysis.
Definition solver.cpp:141
virtual void initializeSolver()=0
Initializes solver state before optimization begins.
double solve(Eigen::VectorX< T > &params)
Solves the optimization problem.
Definition solver.cpp:50
std::vector< double > errorHistory_
History of objective function values over the iterations.
Definition solver.h:139
size_t numParameters_
Total number of parameters in the optimization problem.
Definition solver.h:103
SolverFunctionT< T > * solverFunction_
Function to be optimized.
Definition solver.h:106
virtual void setEnabledParameters(const ParameterSet &parameters)
Specifies which parameters should be optimized.
Definition solver.cpp:40
SolverT(const SolverOptions &options, SolverFunctionT< T > *solver)
Constructor with solver options and function to optimize.
Definition solver.cpp:20
int actualParameters_
Number of parameters currently enabled for optimization.
Definition solver.h:115
#define MT_LOGI_IF(condition,...)
Definition log.h:185
std::bitset< kMaxModelParams > ParameterSet
Bitset for model parameter enablement.
Definition types.h:430
Profiling macros that dispatch to one of three backends, selected at compile time:
#define MT_PROFILE_FUNCTION()
Definition profile.h:110
Common options for numerical optimization solvers.
Definition solver.h:19
size_t minIterations
Minimum number of iterations before checking convergence criteria.
Definition solver.h:21
bool verbose
Enable detailed logging during optimization.
Definition solver.h:30
size_t maxIterations
Maximum number of iterations before terminating.
Definition solver.h:24
float threshold
Convergence threshold for relative error change.
Definition solver.h:27