Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
fully_differentiable_position_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
16#include <algorithm>
17#include <atomic>
18#include <cassert>
19
20namespace momentum {
21
22template <typename T>
24 const SkeletonStateT<T>& skeletonState,
25 const std::vector<PositionConstraintT<T>>& referenceConstraints) {
26 const size_t numConstraints = referenceConstraints.size();
27
28 // resize output arrays
29 position.resize(numConstraints);
30
31 // get joint state
32 const auto& jointState = skeletonState.jointState;
33
34 // go over all locators
35 for (size_t constraintID = 0; constraintID < numConstraints; constraintID++) {
36 // reference for quick access
37 const PositionConstraintT<T>& constraint = referenceConstraints[constraintID];
38
39 // get parent id
40 const size_t& parentId = constraint.parent;
41
42 // transform each locator by its parents transformation and store it in the locator state
43 position[constraintID] = jointState[parentId].transform * constraint.offset.template cast<T>();
44 }
45}
46
49
50template <typename T>
57
58template <typename T>
60 static std::vector<std::string> result = {kWeights, kOffsets, kTargets};
61 return result;
62}
63
64template <typename T>
66 const std::string& name) const {
67 if (name == kWeights) {
68 return constraints_.size();
69 }
70
71 if (name == kOffsets) {
72 return 3 * constraints_.size();
73 }
74
75 if (name == kTargets) {
76 return 3 * constraints_.size();
77 }
78
79 MT_THROW("Unknown input to FullyDifferentiablePositionErrorFunctionT<T>::getInput: {}", name);
80}
81
82template <typename T>
84 const ModelParametersT<T>& /*params*/,
85 const SkeletonStateT<T>& state,
86 const MeshStateT<T>& /* meshState */) {
87 // calculate skeleton- and constraints-state
88 constraintsState_.update(state, constraints_);
89
90 // loop over all constraints and calculate the error
91 double error = 0.0;
92
93 for (size_t i = 0; i < constraints_.size(); ++i) {
94 const PositionConstraintT<T>& ct = constraints_[i];
95 const Eigen::Vector3<T>& position = constraintsState_.position[i];
96
97 // calculate the difference between target and position and error
98 const Eigen::Vector3<T> diff = position - ct.target.template cast<T>();
99 error += ct.weight * diff.squaredNorm() * kPositionWeight;
100 }
101
102 // return error
103 return error * this->weight_;
104}
105
106template <typename T>
108 const ModelParametersT<T>& /*params*/,
109 const SkeletonStateT<T>& state,
110 const MeshStateT<T>& /* meshState */,
111 Ref<Eigen::VectorX<T>> gradient) {
112 const auto& parameterTransform = this->parameterTransform_;
113
114 // calculate skeleton- and constraints-state
115 constraintsState_.update(state, constraints_);
116
117 // storage for joint gradients
118 jointGrad_.setZero(parameterTransform.numAllModelParameters());
119
120 // loop over all constraints and calculate the error
121 double error = 0.0;
122
123 for (size_t i = 0; i < constraints_.size(); ++i) {
124 const PositionConstraintT<T>& ct = constraints_[i];
125 const Eigen::Vector3<T>& position = constraintsState_.position[i];
126 if (ct.weight == 0) {
127 continue;
128 }
129
130 error += calculatePositionGradient(state, constraints_[i], position, jointGrad_);
131 }
132
133 // convert joint gradient to parameter gradient and return
134 gradient.noalias() += jointGrad_ * this->weight_;
135
136 // return error
137 return error * this->weight_;
138}
139
140template <typename T>
142 const ModelParametersT<T>& params,
143 const SkeletonStateT<T>& state,
144 const MeshStateT<T>& /* meshState */,
145 Ref<Eigen::MatrixX<T>> jacobian,
146 Ref<Eigen::VectorX<T>> residual,
147 int& usedRows) {
148 // calculate skeleton- and constraints-state
149 constraintsState_.update(state, constraints_);
150
151 // loop over all constraints and calculate the error
152 double error = 0.0;
153 std::atomic_int offset(0);
154
155 for (size_t i = 0; i < constraints_.size(); ++i) {
156 const PositionConstraintT<T>& ct = constraints_[i];
157 const Eigen::Vector3<T>& position = constraintsState_.position[i];
158 if (ct.weight == 0) {
159 continue;
160 }
161
162 const auto currentOffset = offset.fetch_add(3, std::memory_order_relaxed);
163 error += calculatePositionJacobian(
164 state,
165 constraints_[i],
166 position,
167 jacobian.block(currentOffset, 0, 3, params.size()),
168 residual.middleRows(currentOffset, 3));
169 }
170
171 usedRows = gsl::narrow_cast<int>(jacobian.rows());
172
173 return error;
174}
175
176template <typename T>
177T FullyDifferentiablePositionErrorFunctionT<T>::calculatePositionJacobian(
178 const SkeletonStateT<T>& state,
179 const PositionConstraintT<T>& constr,
180 const Eigen::Vector3<T>& pos,
181 Ref<Eigen::MatrixX<T>> jac,
182 Ref<Eigen::VectorX<T>> res) const {
183 const auto& parameterTransform = this->parameterTransform_;
184
185 MT_CHECK(jac.cols() == static_cast<Eigen::Index>(parameterTransform.transform.cols()));
186 MT_CHECK(jac.rows() == 3);
187
188 // calculate the difference between target and position and error
189 const Eigen::Vector3<T> diff = pos - constr.target;
190 const T wgt = std::sqrt(constr.weight * kPositionWeight * this->weight_);
191
192 // loop over all joints the constraint is attached to and calculate gradient
193 size_t jointIndex = constr.parent;
194 while (jointIndex != kInvalidIndex) {
195 // check for valid index
196 MT_CHECK(jointIndex < this->skeleton_.joints.size());
197
198 const auto& jointState = state.jointState[jointIndex];
199 const size_t paramIndex = jointIndex * kParametersPerJoint;
200 const Eigen::Vector3<T> posd = pos - jointState.translation();
201
202 // calculate derivatives based on active joints
203 for (size_t d = 0; d < 3; d++) {
204 if (this->activeJointParams_[paramIndex + d]) {
205 const Eigen::Vector3<T> jc = jointState.getTranslationDerivative(d) * wgt;
206 for (auto index = parameterTransform.transform.outerIndexPtr()[paramIndex + d];
207 index < parameterTransform.transform.outerIndexPtr()[paramIndex + d + 1];
208 ++index) {
209 jac.col(parameterTransform.transform.innerIndexPtr()[index]) +=
210 jc * parameterTransform.transform.valuePtr()[index];
211 }
212 }
213 if (this->activeJointParams_[paramIndex + 3 + d]) {
214 const Eigen::Vector3<T> jc = jointState.getRotationDerivative(d, posd) * wgt;
215 for (auto index = parameterTransform.transform.outerIndexPtr()[paramIndex + d + 3];
216 index < parameterTransform.transform.outerIndexPtr()[paramIndex + d + 3 + 1];
217 ++index) {
218 jac.col(parameterTransform.transform.innerIndexPtr()[index]) +=
219 jc * parameterTransform.transform.valuePtr()[index];
220 }
221 }
222 }
223 if (this->activeJointParams_[paramIndex + 6]) {
224 const Eigen::Vector3<T> jc = jointState.getScaleDerivative(posd) * wgt;
225 for (auto index = parameterTransform.transform.outerIndexPtr()[paramIndex + 6];
226 index < parameterTransform.transform.outerIndexPtr()[paramIndex + 6 + 1];
227 ++index) {
228 jac.col(parameterTransform.transform.innerIndexPtr()[index]) +=
229 jc * parameterTransform.transform.valuePtr()[index];
230 }
231 }
232
233 // go to the next joint
234 jointIndex = this->skeleton_.joints[jointIndex].parent;
235 }
236
237 res = diff * wgt;
238
239 return wgt * wgt * diff.squaredNorm();
240}
241
242template <typename T>
244 return constraints_.size() * 3;
245}
246
247template <typename T>
249 const PositionConstraintT<T>& constraint) {
250 constraints_.push_back(constraint);
251}
252
253template <typename T>
254const std::vector<PositionConstraintT<T>>&
258
259template <typename T>
260void FullyDifferentiablePositionErrorFunctionT<T>::getInputImp(
261 const std::string& name,
262 Eigen::Ref<Eigen::VectorX<T>> value) const {
263 if (name == kWeights) {
264 for (size_t i = 0; i < constraints_.size(); ++i) {
265 value[i] = static_cast<T>(constraints_[i].weight);
266 }
267 } else if (name == kOffsets) {
268 for (size_t i = 0; i < constraints_.size(); ++i) {
269 value.template segment<3>(3 * i) = constraints_[i].offset;
270 }
271 } else if (name == kTargets) {
272 for (size_t i = 0; i < constraints_.size(); ++i) {
273 value.template segment<3>(3 * i) = constraints_[i].target;
274 }
275 } else {
276 MT_THROW("Unknown input to FullyDifferentiablePositionErrorFunctionT<T>::getInput: {}", name);
277 }
278}
279
280template <typename T>
281void FullyDifferentiablePositionErrorFunctionT<T>::setInputImp(
282 const std::string& name,
283 Eigen::Ref<const Eigen::VectorX<T>> value) {
284 // Normalization is a tricky topic here. When we set the values, we must normalize normals and
285 // quaternions etc because the rest of the code won't work correctly without this (for example
286 // computing the angle between unnormalized vectors requires normalizing them first). However,
287 // if we do normalize the values that are passed in, then the derivatives of those values are
288 // no longer correct. For example, imagine that we pass in v = (1000, 0, 0) as the normal to a
289 // plane. Clearly we must turn this into (1, 0, 0) so the IK solve does something reasonable, but
290 // when we do we find that our dv/dTheta is off by a factor of 1000. It's hard to address that
291 // inside this code, the right way to do it is to require that the inputs be normalized inside
292 // Pytorch before getting passed in, which will ensure all the derivatives work out correctly.
293 if (name == kWeights) {
294 for (size_t i = 0; i < constraints_.size(); ++i) {
295 constraints_[i].weight = static_cast<float>(value[i]);
296 }
297 } else if (name == kOffsets) {
298 for (size_t i = 0; i < constraints_.size(); ++i) {
299 constraints_[i].offset = value.template segment<3>(3 * i);
300 }
301 } else if (name == kTargets) {
302 for (size_t i = 0; i < constraints_.size(); ++i) {
303 constraints_[i].target = value.template segment<3>(3 * i);
304 }
305 } else {
306 MT_THROW("Unknown input to FullyDifferentiablePositionErrorFunctionT<T>::getInput: {}", name);
307 }
308}
309
310template <typename T>
311T FullyDifferentiablePositionErrorFunctionT<T>::calculatePositionGradient(
312 const SkeletonStateT<T>& state,
313 const PositionConstraintT<T>& constr,
314 const Eigen::Vector3<T>& pos,
315 Eigen::VectorX<T>& jGrad) const {
316 const auto& parameterTransform = this->parameterTransform_;
317
318 // calculate the difference between target and position and error
319 const Eigen::Vector3<T> diff = pos - constr.target;
320 const T wgt = constr.weight * 2.0f * kPositionWeight;
321
322 // loop over all joints the constraint is attached to and calculate gradient
323 size_t jointIndex = constr.parent;
324 while (jointIndex != kInvalidIndex) {
325 // check for valid index
326 MT_CHECK(jointIndex < this->skeleton_.joints.size());
327
328 const auto& jointState = state.jointState[jointIndex];
329 const size_t paramIndex = jointIndex * kParametersPerJoint;
330 const Eigen::Vector3<T> posd = pos - jointState.translation();
331
332 // calculate derivatives based on active joints
333 for (size_t d = 0; d < 3; d++) {
334 if (this->activeJointParams_[paramIndex + d]) {
335 // calculate joint gradient
336 const T val = diff.dot(jointState.getTranslationDerivative(d)) * wgt;
337 // explicitly multiply with the parameter transform to generate parameter space gradients
338 for (auto index = parameterTransform.transform.outerIndexPtr()[paramIndex + d];
339 index < parameterTransform.transform.outerIndexPtr()[paramIndex + d + 1];
340 ++index) {
341 jGrad[parameterTransform.transform.innerIndexPtr()[index]] +=
342 val * parameterTransform.transform.valuePtr()[index];
343 }
344 }
345 if (this->activeJointParams_[paramIndex + 3 + d]) {
346 // calculate joint gradient
347 const T val = diff.dot(jointState.getRotationDerivative(d, posd)) * wgt;
348 // explicitly multiply with the parameter transform to generate parameter space gradients
349 for (auto index = parameterTransform.transform.outerIndexPtr()[paramIndex + 3 + d];
350 index < parameterTransform.transform.outerIndexPtr()[paramIndex + d + 3 + 1];
351 ++index) {
352 jGrad[parameterTransform.transform.innerIndexPtr()[index]] +=
353 val * parameterTransform.transform.valuePtr()[index];
354 }
355 }
356 }
357 if (this->activeJointParams_[paramIndex + 6]) {
358 // calculate joint gradient
359 const T val = diff.dot(jointState.getScaleDerivative(posd)) * wgt;
360 // explicitly multiply with the parameter transform to generate parameter space gradients
361 for (auto index = parameterTransform.transform.outerIndexPtr()[paramIndex + 6];
362 index < parameterTransform.transform.outerIndexPtr()[paramIndex + 6 + 1];
363 ++index) {
364 jGrad[parameterTransform.transform.innerIndexPtr()[index]] +=
365 val * parameterTransform.transform.valuePtr()[index];
366 }
367 }
368
369 // go to the next joint
370 jointIndex = this->skeleton_.joints[jointIndex].parent;
371 }
372
373 return constr.weight * diff.squaredNorm() * kPositionWeight;
374}
375
376template <typename T>
377template <typename JetType>
378JetType FullyDifferentiablePositionErrorFunctionT<T>::calculatePositionGradient_dot(
379 const SkeletonStateT<T>& state,
380 const size_t /*iConstr*/,
381 const size_t constrParent,
382 const JetType& constrWeight,
383 const Eigen::Vector3<JetType>& constr_offset,
384 const Eigen::Vector3<JetType>& constr_target,
385 Eigen::Ref<const Eigen::VectorX<T>> vec) const {
386 JetType result;
387
388 const Eigen::Vector3<JetType> pos =
389 state.jointState[constrParent].transform.toAffine3().template cast<JetType>() * constr_offset;
390
391 // calculate the difference between target and position and error
392 const Eigen::Vector3<JetType> diff = pos - constr_target;
393 const JetType wgt = this->weight_ * constrWeight * T(2) * kPositionWeight;
394
395 // loop over all joints the constraint is attached to and calculate gradient
396 size_t jointIndex = constrParent;
397 while (jointIndex != kInvalidIndex) {
398 // check for valid index
399 assert(jointIndex < this->skeleton_.joints.size());
400
401 const auto& jointState = state.jointState[jointIndex];
402 const size_t paramIndex = jointIndex * kParametersPerJoint;
403 const Eigen::Vector3<JetType> posd = pos - jointState.translation();
404
405 // calculate derivatives based on active joints
406 for (size_t d = 0; d < 3; d++) {
407 if (this->activeJointParams_[paramIndex + d]) {
409 diff.dot(jointState.getTranslationDerivative(d)) * wgt,
410 paramIndex + d,
411 this->parameterTransform_,
412 vec);
413 }
414 if (this->activeJointParams_[paramIndex + 3 + d]) {
416 diff.dot(getRotationDerivative(jointState, d, posd)) * wgt,
417 paramIndex + 3 + d,
418 this->parameterTransform_,
419 vec);
420 }
421 }
422 if (this->activeJointParams_[paramIndex + 6]) {
424 diff.dot(getScaleDerivative(jointState, posd)) * wgt,
425 paramIndex + 6,
426 this->parameterTransform_,
427 vec);
428 }
429
430 // go to the next joint
431 jointIndex = this->skeleton_.joints[jointIndex].parent;
432 }
433
434 return result;
435}
436
437template <typename T>
439 const std::string& inputName,
440 const ModelParametersT<T>& /*modelParams*/,
441 const SkeletonStateT<T>& state,
442 Eigen::Ref<const Eigen::VectorX<T>> inputVec) {
443 // Use automatic differentiation on the gradient function:
444 if (inputName == kWeights) {
445 Eigen::VectorX<T> result = Eigen::VectorX<T>::Zero(constraints_.size());
446 using JetType = ceres::Jet<T, 1>;
447 for (size_t iCons = 0; iCons < constraints_.size(); ++iCons) {
448 const auto& cons = constraints_[iCons];
449 result(iCons) = calculatePositionGradient_dot<JetType>(
450 state,
451 iCons,
452 cons.parent,
453 JetType(cons.weight, 0),
454 cons.offset.template cast<JetType>(),
455 cons.target.template cast<JetType>(),
456 inputVec)
457 .v[0];
458 }
459 return result;
460 } else if (inputName == kOffsets) {
461 Eigen::VectorX<T> result = Eigen::VectorX<T>::Zero(3 * constraints_.size());
462 using JetType = ceres::Jet<T, 3>;
463 for (size_t iCons = 0; iCons < constraints_.size(); ++iCons) {
464 const auto& cons = constraints_[iCons];
465 result.template segment<3>(3 * iCons) = calculatePositionGradient_dot<JetType>(
466 state,
467 iCons,
468 cons.parent,
469 JetType(cons.weight),
470 buildJetVec<T, 3>(cons.offset.template cast<T>()),
471 cons.target.template cast<JetType>(),
472 inputVec)
473 .v;
474 }
475 return result;
476 } else if (inputName == kTargets) {
477 Eigen::VectorX<T> result = Eigen::VectorX<T>::Zero(3 * constraints_.size());
478 using JetType = ceres::Jet<T, 3>;
479 for (size_t iCons = 0; iCons < constraints_.size(); ++iCons) {
480 const auto& cons = constraints_[iCons];
481 const auto dotProd = calculatePositionGradient_dot<JetType>(
482 state,
483 iCons,
484 cons.parent,
485 JetType(cons.weight),
486 cons.offset.template cast<JetType>(),
487 buildJetVec<T, 3>(cons.target.template cast<T>()),
488 inputVec);
489 result.template segment<3>(3 * iCons) = dotProd.v;
490 }
491 return result;
492 } else {
493 MT_THROW(
494 "Unknown input name in FullyDifferentiablePositionErrorFunctionT<T>::d_gradient_d_input_dot: {}",
495 inputName);
496 }
497}
498
501
502} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
double getGradient(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &, Ref< Eigen::VectorX< T > > gradient) final
Eigen::VectorX< T > d_gradient_d_input_dot(const std::string &inputName, const ModelParametersT< T > &params, const SkeletonStateT< T > &state, Eigen::Ref< const Eigen::VectorX< T > > inputVec) final
const std::vector< PositionConstraintT< T > > & getConstraints() const
double getError(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &) final
FullyDifferentiablePositionErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
double getJacobian(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &, Ref< Eigen::MatrixX< T > > jacobian, Ref< Eigen::VectorX< T > > residual, int &usedRows) final
SkeletonErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
const ParameterTransform & parameterTransform_
#define MT_THROW(...)
Throws a std::runtime_error with a formatted message.
Definition exception.h:31
SkeletonT< float > Skeleton
Definition fwd.h:263
T times_parameterTransform_times_v(const T &value, const size_t jointParamIdx, const ParameterTransform &parameterTransform, Eigen::Ref< const Eigen::VectorX< T2 > > v)
Eigen::Ref< T > Ref
Definition types.h:43
Eigen::Vector3< T > getScaleDerivative(const JointStateT< T2 > &js, const Eigen::Vector3< T > &ref)
Eigen::Matrix< ceres::Jet< T, N >, N, 1 > buildJetVec(const Eigen::Matrix< T, N, 1 > &v)
ParameterTransformT< float > ParameterTransform
Definition fwd.h:244
Eigen::Vector3< T > getRotationDerivative(const JointStateT< T2 > &js, const size_t index, const Eigen::Vector3< T > &ref)
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
decltype(auto) cast(const ContainerType< ObjectType > &originalContainer)
Casts the scalar type of objects in a container that support the cast<>() method.
Definition types.h:466
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE auto size() const
Definition types.h:87
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
void update(const SkeletonStateT< T > &skeletonState, const std::vector< PositionConstraintT< T > > &referenceConstraints)
Vector3< T > offset
Positional offset in the parent joint space.
size_t parent
Parent joint index this constraint is under.
Represents the complete state of a skeleton.
JointStateListT< T > jointState
Computed joint states for all joints in the skeleton.