Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
gauss_newton_solver_sparse.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
12
13namespace momentum {
14
15template <typename T>
17 const SolverOptions& options,
18 SolverFunctionT<T>* solver)
19 : SolverT<T>(options, solver) {
20 // Set default values from SparseGaussNewtonSolverOptions
23
24 // Update values based on provided options
25 setOptions(options);
26}
27
28template <typename T>
29std::string_view SparseGaussNewtonSolverT<T>::getName() const {
30 return "SparseGaussNewton";
31}
32
33template <typename T>
36
37 if (const auto* derivedOptions = dynamic_cast<const SparseGaussNewtonSolverOptions*>(&options)) {
38 regularization_ = derivedOptions->regularization;
39 doLineSearch_ = derivedOptions->doLineSearch;
40 useBlockJtJ_ = derivedOptions->useBlockJtJ;
41 directSparseJtJ_ = derivedOptions->directSparseJtJ;
42 }
43}
44
45template <typename T>
47 // This is called from the solver base class .solve()
48 this->newParameterPattern_ = true;
49}
50
51template <typename T>
54
55 Eigen::VectorX<T> delta;
56
57 if (!directSparseJtJ_) { // make a dense matrix and sparsify later
58 if (useBlockJtJ_) {
59 // get JtJ and JtR pre-computed
60 {
61 MT_PROFILE_EVENT("Get sparse JtJ and JtR");
62 this->error_ = this->solverFunction_->getJtJR(this->parameters_, hessianApprox_, JtR_);
63 }
64
65 {
66 MT_PROFILE_EVENT("Sparsify JtJ");
67 // sparsify the system
68 JtJ_ = hessianApprox_.sparseView();
69 }
70 } else {
71 MT_PROFILE_EVENT("Sparse gauss newton step");
72
73 // get the jacobian and residual
74 size_t size = 0;
75 {
76 MT_PROFILE_EVENT("get Jacobian");
77 this->error_ =
78 this->solverFunction_->getJacobian(this->parameters_, jacobian_, residual_, size);
79 }
80
81 // sparsify the system
82 const Eigen::SparseMatrix<T> sjac =
83 jacobian_.topLeftCorner(size, this->actualParameters_).sparseView();
84 JtR_.noalias() = sjac.transpose() * residual_.head(size);
85
86 JtJ_ = sjac.transpose() * sjac;
87 }
88 } else { // directly sparse JtJ
89 MT_PROFILE_EVENT("Get sparse JtJ and JtR");
90 this->error_ = this->solverFunction_->getJtJR_Sparse(this->parameters_, JtJ_, JtR_);
91 }
92
93 if (D_.innerSize() != static_cast<Eigen::Index>(this->actualParameters_)) {
94 D_.resize(this->actualParameters_, this->actualParameters_);
95 D_.setIdentity();
96 }
97 JtJ_ += D_ * regularization_;
98
99 // Symbolic decomposition, only needed if the params pattern changed
100 if (this->newParameterPattern_) {
101 MT_PROFILE_EVENT("Sparse analyze");
102 lltSolver_.analyzePattern(JtJ_);
103 this->newParameterPattern_ = !directSparseJtJ_; // works fine for sparse matrix with explicit 0s
104 }
105
106 // Numerical update with the new coefficients
107 {
108 MT_PROFILE_EVENT("Sparse factorization");
109 lltSolver_.factorize(JtJ_);
110 }
111
112 // Solve, compute the gauss-newton step
113 {
114 MT_PROFILE_EVENT("Sparse solve");
115 delta.setZero(this->numParameters_);
116 delta.head(this->actualParameters_) = lltSolver_.solve(JtR_);
117 }
118
119 updateParameters(delta);
120
121 {
122 MT_PROFILE_EVENT("Store history");
123 if (this->storeHistory) {
124 this->iterationHistory_["solver_err"].setZero(1, 1);
125 if (lltSolver_.info() != Eigen::Success) {
126 this->iterationHistory_["solver_err"](0, 0) = 1.0;
127 }
128
129 this->iterationHistory_["jtr_norm"].resize(1, 1);
130 this->iterationHistory_["jtr_norm"](0, 0) = JtR_.norm();
131 }
132 }
133}
134
135template <typename T>
136void SparseGaussNewtonSolverT<T>::updateParameters(Eigen::VectorX<T>& delta) {
137 if (!doLineSearch_) {
138 MT_PROFILE_EVENT("Update params");
139 this->solverFunction_->updateParameters(this->parameters_, delta);
140 return;
141 }
142
143 MT_PROFILE_EVENT("Line search");
144
145 static constexpr T kC1 = 1e-3;
146 static constexpr T kTau = 0.5;
147 static constexpr size_t kMaxLineSearchSteps = 10;
148
149 const T scaledError = kC1 * this->error_;
150 const Eigen::VectorX<T> parametersOrig = this->parameters_;
151 T lineSearchScale = 1.0;
152
153 for (size_t i = 0; i < kMaxLineSearchSteps && std::isnormal(lineSearchScale); ++i) {
154 this->parameters_ = parametersOrig;
155
156 this->solverFunction_->updateParameters(this->parameters_, lineSearchScale * delta);
157
158 const double errorNew = this->solverFunction_->getError(this->parameters_);
159 if ((this->error_ - errorNew) >= lineSearchScale * scaledError) {
160 break;
161 }
162
163 // Reduce step size:
164 lineSearchScale *= kTau;
165 }
166}
167
170
171} // namespace momentum
Abstract base class for optimization objective functions.
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
std::unordered_map< std::string, Eigen::MatrixX< T > > iterationHistory_
Recorded data from optimization process.
Definition solver.h:137
Eigen::VectorX< T > parameters_
Current parameter values.
Definition solver.h:109
bool storeHistory
Whether to record optimization progress for analysis.
Definition solver.h:132
double error_
Current objective function value.
Definition solver.h:126
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
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
Sparse implementation of the Gauss-Newton optimization algorithm.
std::string_view getName() const override
Returns "SparseGaussNewton" as the solver name.
void setOptions(const SolverOptions &options) final
Updates solver configuration, handling both base and sparse Gauss-Newton specific options.
void initializeSolver() final
Initializes solver state before optimization begins.
void doIteration() final
Performs one iteration of the sparse Gauss-Newton algorithm.
SparseGaussNewtonSolverT(const SolverOptions &options, SolverFunctionT< T > *solver)
Creates a solver with the specified options and function to optimize.
Profiling macros that dispatch to one of three backends, selected at compile time:
#define MT_PROFILE_EVENT(NAME)
Definition profile.h:112
#define MT_PROFILE_FUNCTION()
Definition profile.h:110
Common options for numerical optimization solvers.
Definition solver.h:19
Extended options specific to the sparse Gauss-Newton optimization algorithm.
float regularization
Damping parameter added to Hessian diagonal for numerical stability; see https://en....
bool doLineSearch
Enables backtracking line search to ensure error reduction at each step.