Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
solver_function.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
12namespace momentum {
13
14template <typename T>
15void SolverFunctionT<T>::getHessian(const VectorX<T>& parameters, MatrixX<T>& hessian) {
16 (void)parameters;
17 (void)hessian;
18 MT_THROW("SolverFunctionT::getHessian() is not implemented");
19}
20
21template <typename T>
23 const VectorX<T>& parameters,
24 MatrixX<T>& jacobian,
25 VectorX<T>& residual,
26 size_t& actualRows) {
28
29 const size_t numBlocks = getJacobianBlockCount();
30
31 // Calculate total size
32 size_t totalRows = 0;
33 for (size_t i = 0; i < numBlocks; ++i) {
34 totalRows += getJacobianBlockSize(i);
35 }
36 // Add padding for alignment
37 totalRows = padToSimdAlignment(totalRows);
38
39 // Resize if needed
40 if (totalRows > static_cast<size_t>(jacobian.rows()) || parameters.size() != jacobian.cols()) {
41 jacobian.resize(totalRows, parameters.size());
42 residual.resize(totalRows);
43 }
44
45 jacobian.setZero();
46 residual.setZero();
47
48 double error = 0.0;
49 size_t position = 0;
50 actualRows = totalRows;
51
52 // Assemble blocks into full Jacobian
53 for (size_t i = 0; i < numBlocks; ++i) {
54 const size_t blockSize = getJacobianBlockSize(i);
55 if (blockSize == 0) {
56 continue;
57 }
58
59 size_t blockActualRows = 0;
60
61 auto jacBlock = jacobian.block(position, 0, blockSize, parameters.size());
62 auto resBlock = residual.segment(position, blockSize);
63
64 error += computeJacobianBlock(parameters, i, jacBlock, resBlock, blockActualRows);
65
66 position += blockSize;
67 }
68
70 return error;
71}
72
73template <typename T>
74double SolverFunctionT<T>::getJtJR(const VectorX<T>& parameters, MatrixX<T>& jtj, VectorX<T>& jtr) {
76
77 const size_t numBlocks = getJacobianBlockCount();
78
79 // Calculate total Jacobian size
80 const size_t numParams = parameters.size();
81
83 jtr.setZero(actualParameters_);
84
85 // Block compute JtJ and JtR on the fly
86 double error = 0.0;
87
88 for (size_t i = 0; i < numBlocks; ++i) {
89 const size_t blockSize = padToSimdAlignment(getJacobianBlockSize(i));
90 if (blockSize == 0) {
91 continue;
92 }
93
94 size_t blockActualRows = 0;
95
96 tJacobian_.resizeAndSetZero(blockSize, numParams);
97 tResidual_.resizeAndSetZero(blockSize);
98
99 auto jacBlock = tJacobian_.mat().block(0, 0, blockSize, numParams);
100 auto resBlock = tResidual_.vec().segment(0, blockSize);
101
102 error += computeJacobianBlock(parameters, i, jacBlock, resBlock, blockActualRows);
103
104 // Update JtJ and JtR
105 if (blockActualRows == 0) {
106 continue;
107 }
108
109 const auto JtBlock =
110 tJacobian_.mat().block(0, 0, blockActualRows, actualParameters_).transpose();
111
112 // Efficiently update JtJ using selfadjointView with rankUpdate
113 jtj.template selfadjointView<Eigen::Lower>().rankUpdate(JtBlock);
114
115 // Update JtR
116 jtr.noalias() += JtBlock * tResidual_.vec().segment(0, blockActualRows);
117 }
118
120 return error;
121}
122
123template <typename T>
125 const VectorX<T>& parameters,
126 SparseMatrix<T>& jtj,
127 VectorX<T>& jtr) {
128 // mostly a template here. See the actual derived function for implementation (e.g.,
129 // batchSkeletonSolverFunction.cpp)
130 (void)parameters;
131 (void)jtj;
132 (void)jtr;
133 return 0.0;
134};
135
136template <typename T>
138 const VectorX<T>& parameters,
139 MatrixX<T>& hess,
140 VectorX<T>& grad) {
141 // default implementation returns JtJ, JtR
142 return getJtJR(parameters, hess, grad);
143}
144
145template <typename T>
147
148template <typename T>
150 return numParameters_;
151}
152
153template <typename T>
157
158template <typename T>
160 std::unordered_map<std::string, MatrixX<T>>& history,
161 size_t iteration,
162 size_t maxIterations_) {
163 // unused variables
164 (void)history;
165 (void)iteration;
166 (void)maxIterations_;
167}
168
169template <typename T>
171 // Default implementation does nothing
172}
173
174template class SolverFunctionT<float>;
175template class SolverFunctionT<double>;
176
177} // namespace momentum
Abstract base class for optimization objective functions.
double getJacobian(const VectorX< T > &parameters, MatrixX< T > &jacobian, VectorX< T > &residual, size_t &actualRows)
Computes the Jacobian matrix for least squares problems.
size_t getActualParameters() const
Returns the number of parameters currently enabled for optimization.
size_t getNumParameters() const
Returns the total number of parameters in the optimization problem.
virtual double computeJacobianBlock(const VectorX< T > &parameters, size_t blockIndex, Eigen::Ref< MatrixX< T > > jacobianBlock, Eigen::Ref< VectorX< T > > residualBlock, size_t &actualRows)=0
Computes a specific Jacobian block.
virtual double getSolverDerivatives(const VectorX< T > &parameters, MatrixX< T > &hess, VectorX< T > &grad)
Computes derivatives needed by the solver.
virtual double getJtJR_Sparse(const VectorX< T > &parameters, SparseMatrix< T > &jtj, VectorX< T > &jtr)
Computes sparse JᵀJ and JᵀR for large-scale problems.
size_t actualParameters_
Number of parameters currently enabled for optimization.
ResizeableMatrix< T > tResidual_
virtual void initializeJacobianComputation(const VectorX< T > &parameters)=0
Initializes Jacobian computation for the given parameters.
virtual void getHessian(const VectorX< T > &parameters, MatrixX< T > &hessian)
Computes the Hessian matrix of second derivatives.
size_t numParameters_
Total number of parameters in the optimization problem.
virtual double getJtJR(const VectorX< T > &parameters, MatrixX< T > &jtj, VectorX< T > &jtr)
Computes JᵀJ and JᵀR for Gauss-Newton optimization.
virtual void setEnabledParameters(const ParameterSet &parameterSet)
Specifies which parameters should be optimized.
virtual size_t getJacobianBlockCount() const =0
Returns the number of Jacobian blocks available.
virtual void storeHistory(std::unordered_map< std::string, MatrixX< T > > &history, size_t iteration, size_t maxIterations_)
Records solver state for debugging and analysis.
virtual void finalizeJacobianComputation()
Optional cleanup after all Jacobian blocks have been computed.
ResizeableMatrix< T > tJacobian_
Pre-allocated temporary storage for block-wise JtJ computation.
virtual size_t getJacobianBlockSize(size_t blockIndex) const =0
Returns the maximum number of rows for a specific Jacobian block.
#define MT_THROW(...)
Throws a std::runtime_error with a formatted message.
Definition exception.h:31
constexpr size_t padToSimdAlignment(size_t size)
Pads a row count to be a multiple of kJacobianRowAlignment for SIMD alignment.
Eigen::Matrix< T, Dynamic, Dynamic > MatrixX
Dynamic-size, column-major dense matrix.
Definition types.h:80
Vector< T, Dynamic > VectorX
Dynamic-size column vector. Common return type for solver residuals and parameter vectors.
Definition types.h:207
Eigen::SparseMatrix< T > SparseMatrix
Column-major sparse matrix.
Definition types.h:183
std::bitset< kMaxModelParams > ParameterSet
Bitset for model parameter enablement.
Definition types.h:430