Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
finite_difference_sequence_error_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
15
16namespace momentum {
17
18template <typename T>
20 const Skeleton& skel,
21 const ParameterTransform& pt,
22 const std::vector<T>& stencilCoefficients)
23 : SequenceErrorFunctionT<T>(skel, pt), stencilCoefficients_(stencilCoefficients) {
24 MT_CHECK(!stencilCoefficients_.empty(), "Stencil coefficients cannot be empty");
25 targetWeights_.setOnes(skel.joints.size());
26 targetValues_.resize(skel.joints.size(), Eigen::Vector3<T>::Zero());
27}
28
29template <typename T>
31 const Character& character,
32 const std::vector<T>& stencilCoefficients)
34 character.skeleton,
35 character.parameterTransform,
36 stencilCoefficients) {}
37
38template <typename T>
40 targetWeights_.setOnes(this->skeleton_.joints.size());
41 targetValues_.assign(this->skeleton_.joints.size(), Eigen::Vector3<T>::Zero());
42}
43
44template <typename T>
46 MT_CHECK(weights.size() == static_cast<Eigen::Index>(this->skeleton_.joints.size()));
47 targetWeights_ = weights;
48}
49
50template <typename T>
52 const Eigen::Vector3<T>& targetValue) {
53 targetValues_.assign(this->skeleton_.joints.size(), targetValue);
54}
55
56template <typename T>
58 const std::vector<Eigen::Vector3<T>>& targetValues) {
59 MT_CHECK(targetValues.size() == this->skeleton_.joints.size());
60 targetValues_ = targetValues;
61}
62
63template <typename T>
65 std::span<const ModelParametersT<T>> /* modelParameters */,
66 std::span<const SkeletonStateT<T>> skelStates,
67 std::span<const MeshStateT<T>> /* meshStates */) const {
69
70 MT_CHECK(skelStates.size() == stencilCoefficients_.size());
71
72 double error = 0.0;
73
74 for (size_t i = 0; i < this->skeleton_.joints.size(); ++i) {
75 if (targetWeights_[i] == 0) {
76 continue;
77 }
78
79 // Compute derivative using stencil: sum(coeff[k] * pos[k])
80 Eigen::Vector3<T> derivative = Eigen::Vector3<T>::Zero();
81 for (size_t k = 0; k < stencilCoefficients_.size(); ++k) {
82 derivative += stencilCoefficients_[k] * skelStates[k].jointState[i].translation();
83 }
84
85 // Compute residual: derivative - target
86 const Eigen::Vector3<T> residual = derivative - targetValues_[i];
87
88 error += residual.squaredNorm() * targetWeights_[i];
89 }
90
91 return error * this->weight_;
92}
93
94template <typename T>
96 std::span<const ModelParametersT<T>> /* modelParameters */,
97 std::span<const SkeletonStateT<T>> skelStates,
98 std::span<const MeshStateT<T>> /* meshStates */,
99 Eigen::Ref<Eigen::VectorX<T>> gradient) const {
101
102 MT_CHECK(skelStates.size() == stencilCoefficients_.size());
103
104 const Eigen::Index nParam = this->parameterTransform_.numAllModelParameters();
105 MT_CHECK(gradient.size() == static_cast<Eigen::Index>(stencilCoefficients_.size()) * nParam);
106
107 double error = 0.0;
108
109 for (size_t i = 0; i < this->skeleton_.joints.size(); ++i) {
110 if (targetWeights_[i] == 0) {
111 continue;
112 }
113
114 // Compute derivative and residual
115 Eigen::Vector3<T> derivative = Eigen::Vector3<T>::Zero();
116 for (size_t k = 0; k < stencilCoefficients_.size(); ++k) {
117 derivative += stencilCoefficients_[k] * skelStates[k].jointState[i].translation();
118 }
119 const Eigen::Vector3<T> residual = derivative - targetValues_[i];
120
121 const T wgt = targetWeights_[i] * this->weight_;
122 error += residual.squaredNorm() * wgt;
123
124 // Gradient contribution from each frame
125 // d/dp ||residual||^2 = 2 * residual^T * d(residual)/dp
126 // d(residual)/dp = d(derivative)/dp = coeff * d(pos)/dp
127
128 for (size_t frameIdx = 0; frameIdx < stencilCoefficients_.size(); ++frameIdx) {
129 const auto& state = skelStates[frameIdx];
130 const T coeff = stencilCoefficients_[frameIdx];
131
132 // Walk up the kinematic chain for joint i
133 size_t ancestorJointIndex = i;
134 while (ancestorJointIndex != kInvalidIndex) {
135 MT_CHECK(ancestorJointIndex < this->skeleton_.joints.size());
136
137 const size_t paramIndex = ancestorJointIndex * kParametersPerJoint;
138 const Eigen::Vector3<T> posd =
139 state.jointState[i].translation() - state.jointState[ancestorJointIndex].translation();
140
141 // Translation parameters (3)
142 for (size_t d = 0; d < 3; d++) {
143 if (this->activeJointParams_[paramIndex + d]) {
144 const T val = T(2) * wgt * coeff *
145 residual.dot(state.jointState[ancestorJointIndex].getTranslationDerivative(d));
147 val,
148 paramIndex + d,
150 gradient.segment(frameIdx * nParam, nParam));
151 }
152 }
153
154 // Rotation parameters (3)
155 for (size_t d = 0; d < 3; d++) {
156 if (this->activeJointParams_[paramIndex + 3 + d]) {
157 const T val = T(2) * wgt * coeff *
158 residual.dot(state.jointState[ancestorJointIndex].getRotationDerivative(d, posd));
160 val,
161 paramIndex + 3 + d,
163 gradient.segment(frameIdx * nParam, nParam));
164 }
165 }
166
167 // Scale parameter (1)
168 if (this->activeJointParams_[paramIndex + 6]) {
169 const T val = T(2) * wgt * coeff *
170 residual.dot(state.jointState[ancestorJointIndex].getScaleDerivative(posd));
172 val,
173 paramIndex + 6,
175 gradient.segment(frameIdx * nParam, nParam));
176 }
177
178 ancestorJointIndex = this->skeleton_.joints[ancestorJointIndex].parent;
179 }
180 }
181 }
182
183 return error;
184}
185
186template <typename T>
188 // 3 rows per active joint (x, y, z derivative components)
189 const auto nActiveJoints = (targetWeights_.array() != 0).count();
190 return nActiveJoints * 3;
191}
192
193template <typename T>
195 std::span<const ModelParametersT<T>> /* modelParameters */,
196 std::span<const SkeletonStateT<T>> skelStates,
197 std::span<const MeshStateT<T>> /* meshStates */,
198 Eigen::Ref<Eigen::MatrixX<T>> jacobian,
199 Eigen::Ref<Eigen::VectorX<T>> residual,
200 int& usedRows) const {
202
203 MT_CHECK(skelStates.size() == stencilCoefficients_.size());
204
205 const Eigen::Index nParam = this->parameterTransform_.numAllModelParameters();
206 MT_CHECK(jacobian.cols() == static_cast<Eigen::Index>(stencilCoefficients_.size()) * nParam);
207
208 double error = 0.0;
209 Eigen::Index offset = 0;
210
211 for (size_t i = 0; i < this->skeleton_.joints.size(); ++i) {
212 if (targetWeights_[i] == 0) {
213 continue;
214 }
215
216 // Compute derivative and residual
217 Eigen::Vector3<T> derivative = Eigen::Vector3<T>::Zero();
218 for (size_t k = 0; k < stencilCoefficients_.size(); ++k) {
219 derivative += stencilCoefficients_[k] * skelStates[k].jointState[i].translation();
220 }
221 const Eigen::Vector3<T> res = derivative - targetValues_[i];
222
223 const T wgt = targetWeights_[i] * this->weight_;
224 const T sqrtWgt = std::sqrt(wgt);
225
226 error += res.squaredNorm() * wgt;
227 residual.template segment<3>(offset).noalias() = res * sqrtWgt;
228
229 // Jacobian for each frame
230 for (size_t frameIdx = 0; frameIdx < stencilCoefficients_.size(); ++frameIdx) {
231 const auto& state = skelStates[frameIdx];
232 const T coeff = stencilCoefficients_[frameIdx] * sqrtWgt;
233
234 // Walk up the kinematic chain for joint i
235 size_t ancestorJointIndex = i;
236 while (ancestorJointIndex != kInvalidIndex) {
237 MT_CHECK(ancestorJointIndex < this->skeleton_.joints.size());
238
239 const auto& jointState = state.jointState[ancestorJointIndex];
240 const size_t paramIndex = ancestorJointIndex * kParametersPerJoint;
241 const Eigen::Vector3<T> posd = state.jointState[i].translation() - jointState.translation();
242
243 // Translation parameters (3)
244 for (size_t d = 0; d < 3; d++) {
245 if (this->activeJointParams_[paramIndex + d]) {
246 const Eigen::Vector3<T> jc = jointState.getTranslationDerivative(d) * coeff;
248 jc,
249 paramIndex + d,
251 jacobian.block(offset, frameIdx * nParam, 3, nParam));
252 }
253 }
254
255 // Rotation parameters (3)
256 for (size_t d = 0; d < 3; d++) {
257 if (this->activeJointParams_[paramIndex + 3 + d]) {
258 const Eigen::Vector3<T> jc = jointState.getRotationDerivative(d, posd) * coeff;
260 jc,
261 paramIndex + d + 3,
263 jacobian.block(offset, frameIdx * nParam, 3, nParam));
264 }
265 }
266
267 // Scale parameter (1)
268 if (this->activeJointParams_[paramIndex + 6]) {
269 const Eigen::Vector3<T> jc = jointState.getScaleDerivative(posd) * coeff;
271 jc,
272 paramIndex + 6,
274 jacobian.block(offset, frameIdx * nParam, 3, nParam));
275 }
276
277 ancestorJointIndex = this->skeleton_.joints[ancestorJointIndex].parent;
278 }
279 }
280
281 offset += 3;
282 }
283
284 usedRows = gsl::narrow_cast<int>(offset);
285
286 return error;
287}
288
291
292} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
Base class for error functions that penalize finite difference derivatives of joint positions across ...
double getError(std::span< const ModelParametersT< T > > modelParameters, std::span< const SkeletonStateT< T > > skelStates, std::span< const MeshStateT< T > > meshStates) const final
void setTargetValues(const std::vector< Eigen::Vector3< T > > &targetValues)
Set per-joint target values.
double getGradient(std::span< const ModelParametersT< T > > modelParameters, std::span< const SkeletonStateT< T > > skelStates, std::span< const MeshStateT< T > > meshStates, Eigen::Ref< Eigen::VectorX< T > > gradient) const final
void setTargetValue(const Eigen::Vector3< T > &targetValue)
Set a single target value applied to all joints.
double getJacobian(std::span< const ModelParametersT< T > > modelParameters, std::span< const SkeletonStateT< T > > skelStates, std::span< const MeshStateT< T > > meshStates, Eigen::Ref< Eigen::MatrixX< T > > jacobian, Eigen::Ref< Eigen::VectorX< T > > residual, int &usedRows) const final
FiniteDifferenceSequenceErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt, const std::vector< T > &stencilCoefficients)
void setTargetWeights(const Eigen::VectorX< T > &weights)
Set the per-joint weights for the derivative error.
void reset()
Reset weights to ones and target values to zero.
const ParameterTransform & parameterTransform_
SequenceErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
SkeletonT< float > Skeleton
Definition fwd.h:263
void jacobian_jointParams_to_modelParams(const Eigen::Ref< const Eigen::VectorX< T > > &jacobian_jointParams, const Eigen::Index iJointParam, const ParameterTransform &parameterTransform, Eigen::Ref< Eigen::MatrixX< T > > jacobian)
ParameterTransformT< float > ParameterTransform
Definition fwd.h:244
void gradient_jointParams_to_modelParams(const T &grad_jointParams, const Eigen::Index iJointParam, const ParameterTransform &parameterTransform, Eigen::Ref< Eigen::VectorX< T > > gradient)
constexpr size_t kParametersPerJoint
Definition types.h:21
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
Definition types.h:182
Profiling macros that dispatch to one of three backends, selected at compile time:
#define MT_PROFILE_FUNCTION()
Definition profile.h:110
A character model with skeletal structure, mesh, and optional components.
Definition character.h:32
Represents the complete state of a model's mesh.
Definition mesh_state.h:24
A vector of size numModelParams holding the values of all model parameters for a character.
Definition types.h:99
Represents the complete state of a skeleton.
JointList joints
The list of joints in this skeleton, ordered such that every joint's parent appears earlier in the li...
Definition skeleton.h:25